I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Creating number ranges

Posted on

JavaScript doesn’t offer a native range type that could give us a sequence of numbers. To build a range ourselves, we can initialize an array by spreading the keys of another array into it.

We can then map over the array to shift our range up or down. We can also make it follow other patterns, such as having 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]
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]
Debug
none
Grid overlay