Categories
JavaScript Answers

How to Generate Unique Random Numbers Between 1 and 100 with JavaScript?

Spread the love

We can use the while loop to generate a given number of random numbers and put them in an array.

For instance, we can write:

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

We create the arr array which we store the randomly generated numbers in.

Then we have the while loop that checks if arr.length is less than a given number.

Then we generate the number with Math.random with Math.floor if the while loop condition is met.

Since Math.random only generates numbers between 0 and 1, we’ve to multiply the returned result by 100, round it down with Math.floor and add 1 to it.

If the number isn’t already in arr as returned by indexOf , then we call push to add it to arr .

Generate Unique Random Numbers Between 1 and 100 with JavaScript with Sets

We can also use a set instead so we don’t have to check if a number is already in the set.

If it’s already in the set, then it won’t be added again.

For instance, we can write:

const nums = new Set();
while (nums.size !== 8) {
  nums.add(Math.floor(Math.random() * 100) + 1);
}

console.log([...nums]);

We call add to add items to the set.

And we spread the nums set into an array to convert it back to an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *