Sometimes, we want to create an array with random values with JavaScript.
In this article, we’ll look at how to create an array with random values with JavaScript.
How to create an array with random values with JavaScript?
To create an array with random values with JavaScript, we can use the Array
constructor and the Math.random
method.
For instance, we write
const arr = Array(40)
.fill()
.map(() => Math.round(Math.random() * 40));
to call Array
with 40 to create an array with 40 empty slots.
Then we call fill
to fill the slots with undefined
.
And then we call map
with a callback that returns a random number between 0 and 40 for each slot with Math.random
rounded to the nearest integer with Math.round
.
Conclusion
To create an array with random values with JavaScript, we can use the Array
constructor and the Math.random
method.