Multiple ways to create a array with random values in javascript


This is an short tutorial with examples on create an array of random numbers. It also includes without duplicate numbers. An example to get Random value from javascript array

Sometimes, We want to generate a fixed array with random values for testing and debugging.

javascript Random values generate in array

In this example, We will see how to create an random array with size of 10

  • using ES6 Math.random returns a number between 0 and 1, the more number you give, possibility of duplicates is less. This creates an random array of size=10
let randomArray=Array.from({length: 10}, () => Math.floor(Math.random() * 100));
console.log(randomArray) 

Output:

[91,9,6,14,9,82,21,8,72,0]
  • using for loop and push method Math.round returns nearest rounded number
var randomArray = [];
for (let i=0, j=10; i<j; i++) {
    randomArray.push(Math.round(Math.random() * 100))
}
console.log(randomArray)

Output

 [87,12,28,75,68,94,45,36,72,92]

Random array with no repeated values in array

Some times, We don’t want to allow duplicate values in random array,

  • Create an empty array

  • Generate random number using

  • check if this number exists in array, if not found,push to an array

  • if found in array, skip that number by not pushing to it

    Here is an example for random array without duplicates

  var randomArray = [];
for (let i=0, j=10; i<j; i++) {
  let randomNumber=Math.round(Math.random() * 100);
      if (!randomArray.includes(randomNumber)) {
        randomArray.push(randomNumber);
    }
}
console.log(randomArray) 

Output:

[96,20,61,91,80,60,95,33,4,69]

Conclusion

You learned creating random values in array with or without repeated values in multiple ways

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.