Multiple ways to create Random Array in javascript

In this tutorial, We will see how to create a random array with a size of 10, Also covered how to create a random array with no repeated values in an array

This is useful for testing and debugging.

Multiple ways to create Random Array in Javascript

In this example, We will see how to create a random array with no repeated values in an array

  • using ES6, Array.from method used to create an array with length of 10, This method accepts an object and a function. object contains an length of an array, to create an array with length of 10, and function is a callback arrow function, which returns the random number

  • Using Math.random method to generate a random number. It returns a number between 0 and 1, ie. float value such as 0.1234,0.45234 etc.

  • Multiply the random number by 100, so it returns a number between 0 and 100. You can give any number you want, The bigger the number, the possibility of duplicates is less.

  • use Math.floor method to round to the nearest whole number

    This creates a 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 the nearest rounded number

Use for loop and generate Random number with a size of 10. Create an array and push the random number to the array. Prints an array of random numbers with size of 10.

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 an array

Sometimes, We want to generate a random array with no repeated values in an array, for example, Generate random array with no duplicates

Used Array.includes() method to check if the number exists in the array.

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)) {
    randomArray.push(randomNumber);
  }
}
console.log(randomArray);

In the example,

  • Create an empty array to store the random numbers
  • Generate random numbers using Math.random()
  • Use for loop to generate 10 random numbers
  • Use Array.includes method to check if the number exists in the array.
  • This method returns true, if the number exists in the array, skip that number by not pushing to it
  • Returns false, if the number does not exist in the array, push the number to the array.

Output:

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

Conclusion

To Summarize, In this tutorial, We have learned how to create random values in the array with or without repeated values in multiple ways.