How to generate a range of numbers using ES6

Published on

3 min read

Categories associated to this post are: Node JS TypeScript

Using ES6

This is the smallest, one-liner, solution for generating a range of numbers.

JavaScript
[...Array(n)].map((_, i) => from + i * step);

Replace n, from and step with the options you want. Here are a handful of examples:

JavaScript
[...Array(5).keys()];
// Outputs: [0, 1, 2, 3, 4]
 
[...Array(5)].map((_, i) => 1 + i);
// Outputs: [1, 2, 3, 4, 5]
 
[...Array(6)].map((_, i) => 3 + i * 3);
// Outputs: [3, 6, 9, 12, 15, 17]
 
[...Array(4)].map((_, i) => i * 5);
// Outputs: [0, 5, 10, 15]

Using TypeScript

In order for the above examples to work properly in TypeScript you will need to ensure the downlevelIteration option in your tsconfig has been enabled or you can use a slightly different variant as you can see below.

TypeScript
Array.from({ length: n }, (value, key) => from + key * step);

Here is the same examples from above, but with this slightly different variant that TypeScript is happy with.

TypeScript
Array.from({ length: 5 }, (value, key) => key);
// Outputs: [0, 1, 2, 3, 4]
 
Array.from({ length: 5 }, (value, key) => 1 + key);
// Outputs: [1, 2, 3, 4, 5]
 
Array.from({ length: 6 }, (value, key) => 3 + key * 3);
// Outputs: [3, 6, 9, 12, 15, 17]
 
Array.from({ length: 4 }, (value, key) => key * 5);
// Outputs: [0, 5, 10, 15]

Other examples

Range function

JavaScript
const range = (from, to, step = 1) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
 
range(2, 8, 2);
// Outputs: [2, 4, 6, 8]
 
range(2, 10, 2);
// Outputs: [2, 4, 6, 8, 10]
 
range(1, 10);
// Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generator function

This following generator function allows you to specify a start, step and a total count to generate.

JavaScript
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};
 
Array.from(Range(5, -2, -10));
// Outputs: [-10, -12, -14, -16, -18]
 
[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
// Outputs: [-10, -12, -14, -16, -18]
 
// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// Outputs: 10 8 6 4 2

This slightly different generator functions allows you to specify a start, end and step to generate.

JavaScript
const Range = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};
 
[...Range(5, -2, 10)]; // From 10 to 5 with step -2
// Outputs: [10, 8, 6]

Share on social media platforms.