How to generate range of numbers from 0 to n in ES2015 only?
I also found one more intuitive way using Array.from
:
const range = n => Array.from({length: n}, (value, key) => key)
Now this range
function will return all the numbers starting from 0 to n-1
A modified version of the range to support start
and end
is:
const range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);
EDIT As suggested by @marco6, you can put this as a static method if it suits your use case
Array.range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);
and use it as
Array.range(3, 9)
You can use the spread operator on the keys of a freshly created array.
[...Array(n).keys()]
or
Array.from(Array(n).keys())
The Array.from()
syntax is necessary if working with TypeScript