Generate unique random numbers between 1 and 100
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);
- Populate an array with the numbers 1 through 100.
- Shuffle it.
- Take the first 8 elements of the resulting array.
Modern JS Solution using Set (and average case O(n))
const nums = new Set();while(nums.size !== 8) { nums.add(Math.floor(Math.random() * 100) + 1);}console.log([...nums]);