DEV Community

Cover image for 1 line of code: How to create a range array
martin krause
martin krause

Posted on • Updated on

1 line of code: How to create a range array

const createRange = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
Enter fullscreen mode Exit fullscreen mode

Returns a new array with numeric items in the given range.


Optimised code (Benchmark)

const createRange = (a, b, sign = Math.sign(b - a)) =>  Array(Math.abs(b - a + sign)).fill().map((_, i) => a + sign * i);
Enter fullscreen mode Exit fullscreen mode

The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Discussion (10)

Collapse
pengeszikra profile image
Peter Vivo • Edited on
const makeRange = (a, b, sign = Math.sign(b - a)) => 
  Array(Math.abs(b - a + sign))
    .fill()
    .map((_, i) => a + sign * i)
  ;

// makeRange(3, -4) -> [3, 2, 1, 0, -1, -2, -3, -4]
Enter fullscreen mode Exit fullscreen mode

Maybe can write in single line.

Collapse
martinkr profile image
martin krause Author

Check the Benchmark). I updated the article and the code with your solution.

Collapse
martinkr profile image
martin krause Author

Hi,
thank you for your contribution.
Nice code - I'll set up a benchmark.and compare all suggestions so we can find the fastest one.
Cheers!

Cheers!

Collapse
jonrandy profile image
Jon Randy

Not really a one-liner, but it is possible to make a range syntax like this in JS:

1[to(6)]   // [1, 2, 3, 4, 5, 6]
9[to(5)]   // [9, 8, 7, 6, 5]
2[to(8, {step: 2})]   // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

If you want to know how - take a look at my post

Collapse
martinkr profile image
martin krause Author

Amazing series!

Collapse
jonrandy profile image
Jon Randy

More to come when I have some time: String and Array extensions

Thread Thread
martinkr profile image
martin krause Author

nice!

Collapse
gaoryrt profile image
gaoryrt
const createRange = (from, to) => [...Array(to + 1).keys()].slice(from);
Enter fullscreen mode Exit fullscreen mode
Collapse
martinkr profile image
martin krause Author

Check the Benchmark) if you like.

Collapse
martinkr profile image
martin krause Author

Hi,
thank you for your contribution.
Nice code - I'll set up a benchmark.

Cheers!