Multiple ways to create Random Array in javascript

It is a short tutorial with examples of creating an array of random numbers. It also includes duplicate numbers and examples to get Random values from the javascript array.

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

javascript Random values generate an array

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

  • using ES6 Math.random returns a number between 0 and 1, the more number you give, the possibility of duplicates is less. This creates a 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 the 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 an array

Sometimes, We don’t want to allow duplicate values in a random array,

  • Create an empty array

  • Generate random numbers using

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

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

    Here is an example of the 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 to create random values in the array with or without repeated values in multiple ways.