Skip to content

Instantly share code, notes, and snippets.

@pokk
Created May 16, 2017 01:34
Show Gist options
  • Save pokk/d61b34718c47a56321c34a5c586255b1 to your computer and use it in GitHub Desktop.
Save pokk/d61b34718c47a56321c34a5c586255b1 to your computer and use it in GitHub Desktop.
Create array from 0 to N-1 in Javascript

Introduction

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

Ref

  1. http://infoheap.com/javascript-create-array-from-0-to-n-1/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment