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:
xxxxxxxxxx
1
var array = [];
2
3
var startNumber = 1;
4
var endNumber = 3;
5
6
for (var i = startNumber; i <= endNumber; ++i) {
7
array.push(i);
8
}
9
10
console.log(array); // [ 1, 2, 3 ]
Note:
The
startNumber
can't be higher thanendNumer
and they both have to be integers.
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.
xxxxxxxxxx
1
const createArray = (start, end) => {
2
const array = [];
3
if (end > start) {
4
for (let i = start; i <= end; ++i) {
5
array.push(i);
6
}
7
} else {
8
for (let i = start; i >= end; --i) {
9
array.push(i);
10
}
11
}
12
return array;
13
};
14
15
16
// Usage example:
17
18
const array1 = createArray(0, 2);
19
const array2 = createArray(2, 4);
20
const array3 = createArray(2, 0);
21
22
console.log(array1); // [ 0, 1, 2 ]
23
console.log(array2); // [ 2, 3, 4 ]
24
console.log(array3); // [ 2, 1, 0 ]