Fill an array with random numbers in Javascript

 Some of you might think that what we explained in the article on how to fill an array with numbers, apart from the didactic part, would not have much applicability since we load an array with the same number. If it is true that the use cases are less, but so that you can get a real benefit from it, we are going to see how we can fill an array with random numbers in Javascript. In this way, each of the elements of the array that 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 will be the one 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 of the array. This second parameter will play a main role when filling the elements of the array. And thisArg is the value to use as this in the map function.

Once we know how the .from () method works
let’s see how we have to fill it in. The first thing will be to give you 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 we will write it in an abbreviated way with an instantiation of the array 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 positions of the array. That is why this is where we return the random number.
function () {
    return Math.floor (Math.random () * 10);
}

For the random number we have used the .random () method
of the Math object
as we explained in how to generate random numbers in Javascript.

We can abbreviate this function with the arrow operator as follows:
() => Math.floor (Math.random () * 10)

Thus, if we compose our .from () method
it will be as follows:
let myiarray = Array.from ({length: 10}, () => Math.floor (Math.random () * 10));

Now we will only have to show the array filled with the random numbers
let myiarray = Array.from ({length: 10}, () => Math.floor (Math.random () * 10));
myiarray.forEach (function (item, index, arr) {
    console.log (item);
});

So we have seen that with a single function and a little skill we have managed to fill an array with random numbers in Javascript.

Be the first to comment

Leave a Reply

Your email address will not be published.


*