Initialize an array with range 0 to N in JavaScript
This post will discuss how to initialize an array with a range from 0 to N in JavaScript.
There are several ways to create a numbered integer array from 0 (inclusive) to N (exclusive), incremented by step 1, where the value N is dynamic.
1. Using ES6 Spread operator
|
1 2 3 4 5 6 7 |
var n = 5; var arr = [...Array(n).keys()]; console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
2. Using Underscore range() method
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore'); var n = 5; var arr = _.range(n); console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
3. Using Array.from() function
|
1 2 3 4 5 6 7 |
var n = 5; var arr = Array.from({length: n}, (item, index) => index); console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
Alternatively, using Array.from() with Array.prototype.keys() method in ES6.
|
1 2 3 4 5 6 7 |
var n = 5; var arr = Array.from(Array(n).keys()); console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
4. Using Array.prototype.map() function
|
1 2 3 4 5 6 7 |
var n = 5; var arr = [...Array(n)].map((item, index) => index); console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
5. Using Function.prototype.apply() function
|
1 2 3 4 5 6 7 |
var n = 5; var arr = Array.apply(null, {length: n}).map(Number.call, Number); console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
6. Using array literal notation
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var n = 5; var arr = []; for (var i = 0; i < n; i++) { arr.push(i); } console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
7. Using Array Constructor
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var n = 5; var arr = new Array(n); for (var i = 0; i < n; i++) { arr[i] = i; } console.log(arr); /* Output: [ 0, 1, 2, 3, 4 ] */ |
That’s all about initializing an array with a range of 0 to N in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)