Javascript – create array from 0 to N-1 in nodejs

In Javascript to create an array of number from 0 to n-1, we can use spread operator. It is part of ECMAScript (version 6). Currently IE does not have good support for it. It can be used in node scripts safely though.

array of number from 0 to n-1

We can use array of empty values and keys function. Note that Array(10) generates array of empty values of size 10.

var arr = [...Array(10).keys()]
console.log("arr=" + arr);
arr=0,1,2,3,4,5,6,7,8,9
Env: node version v5.12.0

array of number from 1 to n

In case you need 1 to N array, you can use keys and map on array of empty value. Note that we are using arrow function here which is supported by Chrome and Firefox currently.

var arr = [...Array(10).keys()].map(x => x+1);
console.log("arr=" + arr);
arr=1,2,3,4,5,6,7,8,9,10
Env: node version v5.12.0

The following can also be used:

var arr = [...Array(10)].map((x,i) => i+1);
console.log("arr=" + arr);
arr=1,2,3,4,5,6,7,8,9,10
Env: node version v5.12.0

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments