DEV Community

Dom Habersack
Dom Habersack

Posted on • Originally published at islovely.co

🔥 Create number ranges in JavaScript

To get a range of numbers in JavaScript, initialize an array by spreading the keys of another array into it. You can shift the range up or down, or do things like have it contain only even numbers.

const range = [...Array(5).keys()] // ⇒ [0, 1, 2, 3, 4]

// the number in `Array(number)` describes how many values you want
[...Array(7).keys()] // ⇒ [0, 1, 2, 3, 4, 5, 6]

// you can `map` the values to shift or otherwise manipulate the range
[...Array(4).keys()].map(n => n + 3) // ⇒ [3, 4, 5, 6]
[...Array(4).keys()].map(n => n - 3) // ⇒ [-3, -2, -1, 0]
[...Array(4).keys()].map(n => n * 2) // ⇒ [0, 2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Oldest comments (6)

Collapse
 
hardikchopra profile image
Hardik Chopra

Very effective shortcut 🔥

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo • Edited

Why not

Array(5).fill(0).map((_, i) => I)
Enter fullscreen mode Exit fullscreen mode

Instead of keys and destructuring

Collapse
 
domhabersack profile image
Dom Habersack

I find the shorter version easier to read, but I’d go with your line if performance was more important. 👍 Thanks for sharing it!

Collapse
 
joshuakb2 profile image
Joshua Baker

I always copy and paste one of these:

function range(n) {
    let r = [];
    for (let i = 0; i < n; i++) r.push(i);
    return r;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
domhabersack profile image
Dom Habersack

Nice yes, putting this in a helper function is definitely the way to go.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Easier way:

const getRange = (e) => 
   Array.from({length:e},(v, i)=> i+1);

getRange(4); // [ 1, 2, 3, 4 ]
Enter fullscreen mode Exit fullscreen mode

But one nice to have in ranges is to be able to define both the initial and the end values, hence:

const getRangeBetween = (ini, end) => 
   Array.from({length:end},(v, i)=> i+1).filter( x => x > ini && x < end);

getRangeBetween(2, 9) // [ 3, 4, 5, 6, 7, 8 ]
Enter fullscreen mode Exit fullscreen mode

You can also made it inclusive by doing

const getRangeBetween = (ini, end) => 
   Array.from({length:end},(v, i)=> i+1).filter( x => x >= ini && x <= end);

getRangeBetween(2, 9) // [ 2, 3, 4, 5, 6, 7, 8, 9 ]
Enter fullscreen mode Exit fullscreen mode

Only "bad thing" is that this method doesn't work for negative numbers neither for getting a float range (at least this alone).

You can use map for that instead of filter, though 😁

Cheers!