Create an array sequence from 1 to N in a single line in JavaScript
This post will discuss how to create an array sequence from 1 to N in JavaScript.
There are several ways to create an array sequence of integers from 1 (inclusive) to N (inclusive), where the value N is dynamic.
1. Using Array.from() function
|
1 2 3 4 5 6 7 |
const N = 5; const arr = Array.from({length: N}, (_, index) => index + 1); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
Or use Array Constructor
|
1 2 3 4 5 6 7 |
const N = 5; const arr = Array.from(Array(N), (_, index) => index + 1); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
Or
|
1 2 3 4 5 6 7 |
const N = 5; const arr = Array.from(Array(N+1).keys()).slice(1); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
2. Using Spread operator
|
1 2 3 4 5 6 7 |
const N = 5; const arr = [...Array(N+1).keys()].slice(1); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
or
|
1 2 3 4 5 6 7 |
const N = 5; const arr = [...Array(N).keys()].map(x => ++x); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
or
|
1 2 3 4 5 6 7 |
const N = 5; const arr = [...Array(N)].map((_, index) => index + 1); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
3. Using Underscore Library
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore'); const N = 5; const arr = _.range(1, N+1); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
The _.range method is overloaded to generate a range from start (inclusive) to stop (exclusive), incremented (or decremented) by step.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore'); const start = 1, end = 10, step = 2; const arr = _.range(start, end, step); console.log(arr); /* Output: [ 1, 3, 5, 7, 9 ] */ |
That’s all about creating an array sequence from 1 to N in a single line 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 :)