Home > Software engineering >  Generate array of objects with unique value
Generate array of objects with unique value

Time:06-21

Currently this code generate array with 10 objects with value number and display.The number is random from 0 to 9 so there can be duplicates. Is there a way, where i can get unique(all the objects having different number value ) number only?

const newArray = Array(10)
        .fill()
        .map(() => {
          return { number: Math.floor(Math.random() * 10), display: false };
        });

CodePudding user response:

You need to simply create an array of desired length and fill it with whole numbers and then shuffle the array.

There are different approaches you could take for shuffling an array, one of them is Fisher Yates Shuffle.

function shuffle(array) {
  for (let i = array.length - 1; i > 1; i--) {
    const j = Math.floor(Math.random() * (i   1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

const nums = Array.from({ length: 10 }, (_, i) => i);
shuffle(nums);
console.log(nums);

CodePudding user response:

An answer that does not use shuffling:

const ARRAY_LENGTH = 10;

//create the array [0, 1, ..., ARRAY_LENGTH]
let options = Array.from(Array(ARRAY_LENGTH).keys());

//create the asked for array
let result = Array(ARRAY_LENGTH).fill().map(()=> {
  //pick a random element from the `options` array...
  let optionIndex = Math.floor(Math.random()*options.length);
  let number = options[optionIndex];

  //...remove it from the array (so that it can't be picked again)
  options.splice(optionIndex, 1);

  //use it and continue to next element
  return { number, display: false };
});

console.log(result);

CodePudding user response:

There are different ways to do that.

But i think this would be the most elegant way, because you don't need a second array and you got O(N):

Build an array with 10 numbers. Then iterate through the array. Swap the item with a random choosen item in your area. Voila you have shuffled your array.

var arr = [0, 1, 2 ,3 ,4 ,5 ,6 ,7 ,8, 9];
for (let i = 0; i < arr.length;   i) {
   let rands = Math.floor(Math.random() * 10);
   [arr[i], arr[rands]] = [arr[rands], arr[i]];
} 
console.log(arr);

CodePudding user response:

The complexity is quite high but the code is still fast to execute with 10 values :

const seenNumbers = new Set();
newArray = Array(10)
  .fill()
  .map(() => {
    let number = Math.floor(Math.random() * 10);
    while (seenNumbers.has(number)) {
      number = Math.floor(Math.random() * 10);
    }
    seenNumbers.add(number);
    return { number: number, display: false };
  });
seenNumbers.clear();

console.log(newArray);

  • Related