What are the Different ways to Create Array with Range of Numbers in JavaScript

    Oct 22, 2021       by Suraj Roy

While working with any technology, It often requires to create an array with range of numbers. In JavaScript there are few ways by which same can be done.

In this article, We will see the different ways by which an array of number ranges can be created.

Ways to create Array with a range of Numbers

First way

 

 
function createRange() {
    const range = [...Array(10).keys()]; // It will create array with value 0 to 9
    console.log (range); // Output: [0,1, 2, 3, 4,5, 6, 7, 8, 9]
};
 

 

Second way

 

 
function createRange() {
    const start = 5;
    const end = 15;
    const range = [...Array(end - start + 1).keys()].map(x => x + start); // Create array with 5 - 20
    console.log(range); // Output: [5, 6, 7, 8, 9, 10,11,12,13,14,15] 
};
 

 

Third way

 

 
function createRange() {
    const start = 1;
    const end = 10;
    const range = [...Array(end - start + 1).keys()].map(x => x + start); // Create array with value 1 to 10
    console.log(range);  // Output: [1, 2, 3, 4,5, 6, 7, 8, 9, 10]
};
 

 

Fourth Way

 

 
function createRange() {
    const start = 0;
    const end = 50;
    const step = 5;
    const arrayLength = Math.floor(((end - start) / step)) + 1;
    const range = [...Array(arrayLength).keys()].map(x => (x * step) + start);
    console.log(range); // Output: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
};
 

 


WHAT'S NEW

Find other similar Articles here: