When generating random numbers, there is always the chance of getting duplicates. However as you specifically require 3 random numbers, I'd suggest checking that each number you generate does not already exist in the array of numbers.
I can see you have somewhat attempted to ensure that the same number isn't added twice in a row, however as you call Math.random()
twice, once in the if
and once when you push
the number, you will actually be generating a new number each time.
Try instead using .includes()
to check if the number already exists in the array.
Something like this:
let myArray = [];
function randomNumbers() {
for (let i = 0; i < 3; i++) {
while (!myArray[i]) {
let newRandomInt = Math.floor(Math.random() * 10);
if (!myArray.includes(newRandomInt)) {
myArray.push(newRandomInt)
}
}
}
}
randomNumbers()
console.log(myArray)