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]
Top comments (6)
Why not
Instead of keys and destructuring
I find the shorter version easier to read, but Iād go with your line if performance was more important. š Thanks for sharing it!
Easier way:
But one nice to have in ranges is to be able to define both the initial and the end values, hence:
You can also made it inclusive by doing
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!
I always copy and paste one of these:
Nice yes, putting this in a helper function is definitely the way to go.
Very effective shortcut š„