You could use the Set object. When using the method add(), values cannot be duplicated.
Here is an example:
function random(x, max = 10) { // x = how many random numbers and max = the max number
const set = new Set();
for (let i = 0; i <= x; i++) { // Generate numbers x times
secondLoop:
while(true) { // Run the loop until there is a match
let random = Math.floor(Math.random() * Math.floor(max));
set.add(random); // Set the value
if (set.size === max) { // We have all the values. Let's break the loop
break secondLoop;
}
}
}
return set;
}
console.log(random(10));
console.log(random(10))
returns everything that you need. You could use random(10).values()
, random(10).delete()
or whatever you like.
2
solved How to dedupe pair of random numbers in JavaScript?