EN
JavaScript - create array of all integers between two numbers (inclusive)
0
points
In this article, we would like to show you how to create an array of all integers between two numbers in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var array = [];
var startNumber = 1;
var endNumber = 3;
for (var i = startNumber; i <= endNumber; ++i) {
array.push(i);
}
console.log(array); // [ 1, 2, 3 ]
Note:
The
startNumber
can't be higher thanendNumer
and they both have to be integers.
Reusable arrow function (ES6+)
In this example, we create a reusable arrow function that creates array
of all integers between start
and end numbers
. In this solution, the start
number can be higher than the end
number.
// ONLINE-RUNNER:browser;
const createArray = (start, end) => {
const array = [];
if (end > start) {
for (let i = start; i <= end; ++i) {
array.push(i);
}
} else {
for (let i = start; i >= end; --i) {
array.push(i);
}
}
return array;
};
// Usage example:
const array1 = createArray(0, 2);
const array2 = createArray(2, 4);
const array3 = createArray(2, 0);
console.log(array1); // [ 0, 1, 2 ]
console.log(array2); // [ 2, 3, 4 ]
console.log(array3); // [ 2, 1, 0 ]