Create array from 0 to N

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

Leave a Comment

Your email address will not be published.