Fill Array with Random Numbers in JavaScript

Using Array.from() and Math.random() method

To fill array with random numbers in JavaScript:

  • Use Math.random() to get random numbers between 0 to 1.
  • Use array.from() with length with desired length and mapping function as () => Math.random() * 20. This mapping function will be executed for every element in the array.

Let’s say we want to fill an Array with 10 random numbers. Here is the code:

Output:

Here are the 10 random numbers that we have generated. We set the range to 20, as a result, it filled the array with 10 random numbers 1 between 20.

We multiplied Math.random() by 20, so that we can get random numbers between 1 and 20.

You can round numbers to 2 decimal places in case you need less decimal points.

If you don’t want the floating points, you can simply use the Math.floor() method to avoid them. Here’s the solution to it:

Output:

You result may be different from ours because each time it will generate different numbers.

We used array.from() to create an array and used Math.random() to generate random numbers,

array.from() accepts callback function that helps you to execute mapping function for each elements of array.

Here mapping function is () => Math.random() * 20

Using for loop(), array.push(), and Math.random() Method

To fill array with random numbers:

  • Use for loop to iterate over array of desired length.
  • Use Math.random()*20 to generate random numbers between 1 and 20. You can replace 20 with whatever range you are looking for.
  • Use array.push() method to add new elements at the end of the array.

Follow the below program:

Output:

Fill array with unique random numbers

If you notice the output, you may be able to see that there are repeated numbers in the array. What if we want to fill the array with random numbers that are unique? To do so, follow the below code example:

Output:

We declared empty array and used for loop to iterate over 10 times.

For each iteration, calculated the random number. If it was already present in the array, we skipped it otherwise we pushed into array using push() method.

That’s all about how to fill array with random numbers.

Was this post helpful?

Leave a Reply

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