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));


  • 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))



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)) {




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

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
You'll get a notification every time a post gets published here.