The JavaScript array is an ubiquitous data structure, thus I’d like to spend some time to get more familiar/reacquainted with the Array object. I’ll share my knowledge with you in the form of blog posts.
In this post I’ll create a function that returns an array of random whole numbers.
Let’s get started!
function randomNumbersArray(length = 10) {
// return array of random numbers between 1 and 100
// if length parameter is not provided, length is set to 10
}
We know that we want to create an array of random whole numbers between 1 and 100 with either a specified length or 10. Let’s first discuss the Array constructor.
Calling Array constructor with single number argument
With JavaScript’s Array constructor you are able to call it with a single number argument. If you do this, an array will be created with the length of the number that is received. Each element will be undefined
.
In the example above, I am calling the Array constructor with an argument of 10. As you can see, the length
property is set to 10.
Array.from()
Array.from
is a static method on the JavaScript Array object which will create a new array from an iterable/array-like object.
The first parameter of Array.from
is an object. So we could do something like this:
We call Array.from
with a string, which is an interable object, and an array is created from that value.
Array.from
has an optional second parameter which is a mapping function.
In the example above, we are using the mapping function to capitalize each letter in the first argument.
Putting it all together
Let’s now take what we know about the JavaScript Array and create the randomNumbersArray
function.
function randomNumbersArray(length = 10) {
return Array.from(Array(length), () => Math.floor(Math.random() * 100) + 1);
}
Here’s an example showing the output.
We are calling Array.from
and passing in an array with a length of the value of the length
argument that is created using the Array
constructor as the first param, and we are passing in a mapping function that creates a random whole number between 1 and 100 for each element of the array as the second param.
We now have a function that creates an array, with a length of 10, unless a length argument is provided, of whole numbers between 1 and 100.
Conclusion
Of course there are multiple ways to create an array of random numbers in JavaScript. I thought this approach was interesting as it uses the Array object’s constructor and the from
static method. Thanks for reading! Until next time.