Sometimes, we want to create an array of all integers between two numbers, inclusive, in JavaScript.
In this article, we’ll look at how to create an array of all integers between two numbers, inclusive, in JavaScript.
Create an Array of All Integers Between Two Numbers, Inclusive, in JavaScript
To create an array of all integers between two numbers, inclusive, in JavaScript, we can use the Array.from
method to create an array with a given length and includes integers between 2 numbers.
For instance, we can write:
const arr = Array.from({
length: 5
}, (v, k) => k + 1)
console.log(arr)
to call Array.from
with an object with the length
property to specify the length of the array.
The callback passed in as the 2nd argument returns a number that we want to include.
Therefore, arr
is [1, 2, 3, 4, 5]
.
Conclusion
To create an array of all integers between two numbers, inclusive, in JavaScript, we can use the Array.from
method to create an array with a given length and includes integers between 2 numbers.