Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability since we load an array with the same number. It is true that the use cases are fewer, but in order to get the most out of it we are going to see how we can populate an array with random numbers in JavaScript. This way each of the elements of the array we create by default will be different.
In this case, instead of the .fill()
method, we are going to use the .from()
method. So let's see what is the syntax of the .from()
method
Array.from(arrayLike[, mapFn[, thisArg]])
In this case the first parameter arrayLike
has to be an iterable element that we will convert into an array. The second parameter is mapFn
which will be a map function that will be executed for each element in the array. This second parameter will play a major role in filling the array elements. And thisArg
is the value to use as this in the map function.
Now that we know how the .from()
method works, let's see how to fill it in.
The first thing is to give it an iterable element that has ten elements. So we can create an array with the 10 empty elements.
new Array(10)
But we are going to do it in a different way and write it in a shorthand way with an array instantiation as follows:
{length: 10}
Now we will focus on the map function. This function is the one that will return the value to assign to each of the array positions. That is why it is here where we return the random number.
function() { return Math.floor(Math.random() * 10); }
For the random number we have used the method .random()
of the Math object.
This function can be abbreviated with the arrow operator as follows:
() => Math.floor(Math.random() * 10)
So, if we compose our .from()
method, it will look like this:
let myarray = Array.from({length: 10}, () => Math.floor(Math.random() * 10));
All that remains is to display the array populated with the random numbers.
let myarray = Array.from({length: 10}, () => Math.floor(Math.random() * 10)); myarray.forEach(function(item,index,arr){ console.log(item); });
So we have seen that with a single function and a bit of skill we have managed to fill an array with random numbers in JavaScript.