HomeCreate array from 0 to N

Create array from 0 to N

Published: 5/14/2022

Let's go straight to the point. Sometimes you need an Array instead of a for loop. Here are several ways to do it.

Let's assume we have already defined our N, as, say, const n = 10; Now here are all our options.

Using spread operator and Array.keys

[...Array(n).keys()]

Using the Array.from static method

Array.from({ length: n }, (_, i) => i)

Using Array.from with Array.map

Array.from(Array(n)).map((e, i) => i)

Using Array with .fill and .map

Array(n).fill().map((e, i) => i);

Using underscore library

_.range(n);

About Code with Node.js

This is a personal blog and reference point of a Node.js developer.

I write and explain how different Node and JavaScript aspects work, as well as research popular and cool packages, and of course fail time to time.