Generate unique random numbers between 1 and 100

dotty picture dotty · Mar 4, 2010 · Viewed 192.6k times · Source

How can I generate some unique random numbers between 1 and 100 using JavaScript?

Answer

adam0101 picture adam0101 · Mar 4, 2010

For example: To generate 8 unique random numbers and store them to an array, you can simply do this:

var arr = [];
while(arr.length < 8){
    var r = Math.floor(Math.random() * 100) + 1;
    if(arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);