Skip to content
Advertisement

Array item gets the value “undefined”

I am trying to create an array of unique numbers from 0 to 10:

var numbers=[];
var i=0;
var prevLength=numbers.length;

while(numbers.length<10){
    prevLength=numbers.length;
    if(numbers.length<=prevLength){
        numbers[i]=Math.floor(Math.random()*10);
        numbers=[...new Set(numbers)];
        console.log(numbers);
        i++;
    }
}

But the output of the array will always have an undefined item at a random index which I don’t know why.

[ 9, 1, 8, 7, undefined, 5, 2, 0, 6, 3 ]

Can somebody help me out?

Advertisement

Answer

If the new Set removes a duplicate, then i will be larger than the length of numbers, due to numbers.length shrinking but i still getting increased. Don’t keep track of an index, just use .push to push to the end of the array:

var numbers=[];
var prevLength=numbers.length;

while(numbers.length<10){
    numbers.push(Math.floor(Math.random()*10));
    numbers=[...new Set(numbers)];
    console.log(numbers);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement