Reputation: 55
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?
Upvotes: 0
Views: 44
Reputation: 1570
You can also do this without Set
eg:
var numbers = [];
var rand;
while(numbers.length < 10){
rand = Math.floor(Math.random()*10);
numbers.indexOf(rand) === -1 && numbers[numbers.length] = rand;
}
console.log(numbers);
Upvotes: 0
Reputation: 35512
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);
}
Upvotes: 1
Reputation: 171669
A more efficient way to make use of the Set would be something like:
const set = new Set()
while(set.size < 10){
const rand = Math.floor(Math.random()*10);
!set.has(rand) && set.add(rand);
}
const res = [...set]
console.log(res)
Upvotes: 1
Reputation: 350272
This happens because of this statement:
numbers=[...new Set(numbers)];
This can potentially reduce the length of numbers
, but as you don't align the value of i
with the potential shortening, you'll get gaps.
The solution is to drop the use of numbers[i] =
and use numbers.push
instead:
numbers.push(Math.floor(Math.random()*10));
Upvotes: 1