Generate array with random numbers in JavaScript

In this tutorial, you will see how to generate an array with random numbers in JavaScript. For this purpose, I am going to use math.random function which generates a random value. There are some processes explained below to generate an array with random numbers.

Using fill() and map() method:

The fill() method fills the array with specified values and modifies the original array. The original array can be overwritten by the fill() method. This method returns the modified array.

The map() method creates a new array for each array element by calling a function.

const array = Array(6)
  .fill()
  .map(() => 20 * Math.random());

console.log(array);

In the above program, I have created an array and set the length of the array is 6. You can set the length as you wish.

After that, I used fill() method to fill and get a modified array with specified values.

Then map() method is used to call  Math.random() to generate a random number for each element of the array. It will generate random numbers between 0 to 20.

Output: 

[12.048939937650399, 4.046154574188345, 5.935852248559588, 1.814147075940209, 3.8275124919563135, 7.5750526847358834]

As you can see in the output I got an array with some random float numbers. The length of the array is 6 and all the value is between 0 to 20.

 

  • We can generate integers instead of float numbers by using Math.floor() method.
    const array = Array(6)
        .fill()
        .map(() => Math.floor(20 * Math.random()));
    console.log(array);

     Output:

    [5, 7, 8, 17, 4, 13]

    You can see in the above output I got an array with 6 random integers which are between 0 to 20.

Array.from() method:

The Array.form() method allows us to create a new shallow copied array instance from an array-like or iterable object. This method returns a new array instance.

const array = Array.from({ length: 6 }, () => Math.random() * 20);
console.log(array);

Here, I have used Array.from() method to create and fill the array with random numbers.

And length: 6 to get 6 random numbers in the array.

Output:

[17.584355709602807, 4.592638665589184, 9.169604019402087, 18.911980963502725, 5.550500753145147, 13.721315247919275]

 

  • We can generate integers instead of float numbers by using Math.floor() method.
    const array = Array.from({ length: 6 }, () => Math.floor(Math.random() * 20));
    console.log(array);

    Output:

    [6, 5, 9, 7, 18, 11]

Notes:

To generate integers you can also use Math.round() method instead of math.floor() method.

Leave a Reply

Your email address will not be published. Required fields are marked *