1

I am trying to generate an array using a loop with each value in the array being unique. Specifically, I would like to have five elements in the array, with each being a random number between 1 and 100 (without duplicates).

Is this the right way to do it?

P.S I am a beginner with only 8 days of JS experience.

Thanks in advance!

let arr = []
    let num = 0
    let x = 4
    while (x >= 0) {
        if (arr.indexOf(arr[x]) == arr.lastIndexOf(arr[x])){
        arr.push(Math.floor(Math.random(num)*100))
        } else if (arr.indexOf(arr[x]) !== arr.lastIndexOf(arr[x])) {
            arr.push(Math.floor(Math.random(num)*100))
        } else {
            arr.push(Math.floor(Math.random(num)*100))
        }
        x--
    } 

    console.log(arr)
Sebastian Smiley
  • 831
  • 4
  • 15

1 Answers1

0

The following snippet should produce the behaviour you want.

// Fill an array with the numbers 1-100.
let randomizedArray = []
for (let i = 0; i < 100; i++) {
  randomizedArray.push(i + 1)
}

// Shuffle the array using a Fisher-Yates shuffle.
let m = randomizedArray.length,
  t, r;
while (m) {
  r = Math.floor(Math.random() * m--);
  t = randomizedArray[m];
  randomizedArray[m] = randomizedArray[r];
  randomizedArray[r] = t;
}

// Pop the first 5 elements of the shuffled array into a new array and print it.
let myArray = []
for (let i = 0; i < 5; i++) {
  myArray.push(randomizedArray.pop())
}
console.log(myArray)

For more information on shuffling arrays, see this StackOverflow question.

Sebastian Smiley
  • 831
  • 4
  • 15