Languages
[Edit]
EN

JavaScript - create array of all integers between two numbers (inclusive)

0 points
Created by:
Blessing-D
574

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 than endNumer 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 ]

 

References

  1. Array.prototype.push() - JavaScript | MDN

Alternative titles

  1. JavaScript - create array of elements between two numbers (inclusive)
  2. JavaScript - create array of elements in given range (inclusive)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join