Categories
JavaScript Answers

How to generate unique random numbers between 1 and 100 with JavaScript?

Spread the love

Sometimes, we want to generate unique random numbers between 1 and 100 with JavaScript.

In this article, we’ll look at how to generate unique random numbers between 1 and 100 with JavaScript.

How to generate unique random numbers between 1 and 100 with JavaScript?

To generate unique random numbers between 1 and 100 with JavaScript, we can use the Math.random method.

For instance, we write

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

to use a while loop to put random numbers into the arr array until we have 10 random numbers.

We create the random number between 1 and 100 with

Math.floor(Math.random() * 100) + 1

Then we check if the number is already in arr with

arr.indexOf(r) === -1

If it isn’t, then we call push to push the number into the array.

Conclusion

To generate unique random numbers between 1 and 100 with JavaScript, we can use the Math.random method.

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 *