There’re occasions where we need to generate an array of numbers within the given bounds.
In this article, we’ll look at how to generate a range of numbers within the supplied bounds.
The Array function
We can use the Array
constructor as a regular function to create an array with the given size.
Then we can get the indexes with the keys
method to get the indexes of an array.
For instance, we can write:
const arr = [...Array(5).keys()];
console.log(arr)
We call keys
to return the indexes of the array.
And we spread the items into an array.
Array.from
The Array.from
method is a static method that lets us create an array derived from another array.
We can use it to create a number array by using it to map the values to the ones we want.
For instance, we can write:
const lowerBound = 6;
const arr = Array.from(new Array(10), (x, i) => i + lowerBound);
console.log(arr)
The first argument is the array we want to map from.
And the 2nd argument is the mapping function.
x
is the entry in from the array in the first argument we’re iterating through.
And therefore, we get:
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
as the value of arr
.
Lodash
Lodash has the range
method that lets us create an array with a range of numbers easily.
It takes up to 3 arguments.
The first is the size of the array to create if there’s only one argument.
If we pass in 2 arguments, then the first number is the starting number and the 2nd is the ending number.
And if we pass in 3 arguments, then the first and 2nd arguments are the same as passing in 2 arguments.
And the 3rd argument is the increment between each number.
For instance, if we write:
const arr = _.range(10);
console.log(arr)
then arr
is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.
If we write:
const arr = _.range(1, 11);
console.log(arr)
Then arr
is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.
And if we write:
const arr = _.range(1, 11, 2);
console.log(arr)
then arr
is [1, 3, 5, 7, 9]
.
Conclusion
We can create an array of numbers with the Array
function.
Also, we can use the Array.from
static method.
Another easy way to create a number array is to use Lodash’s range
method.