## DEV Community is a community of 785,073 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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);
``````

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);
``````

## 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.

Photo by zoo_monkey on Unsplash

## Discussion (10)

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]
``````

Maybe can write in single line.

martin krause

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

martin krause

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

Cheers!

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]
``````

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

martin krause

Amazing series!

Jon Randy

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

martin krause

nice!

gaoryrt
``````const createRange = (from, to) => [...Array(to + 1).keys()].slice(from);
``````
martin krause

Check the Benchmark) if you like.

martin krause

Hi,