Borislav Hadzhiev
Sat Oct 09 2021·2 min read
Photo by Kristopher Roller
To create an array containing numbers from 1 to N:
1
.const arr = []; const total = 5; for (let i = 1; i <= total; i++) { arr.push(i); } console.log(arr); // 👉️ [1, 2, 3, 4, 5]
In the for loop we iterate for N times, pushing the value of the i
variable
for the current iteration in the array.
1
, just change the value the i
variable starts at.An alternative and more modern approach is to use the Array.from method.
const total = 5; const arr = Array.from( {length: total}, (_, index) => index + 1 ); console.log(arr) // 👉️ [1, 2, 3, 4, 5]
The parameters we pass to the Array.from
method are:
The use an _
character to denote that we don't need the first parameter of the
function, which is the value of the array element.
A call to Array.from(3)
returns an array with 3 elements with the value of
undefined
.
However, we make use of the index of the array element. Indexes are zero-based
in JavaScript, therefore we have to add 1
to get the desired result.
Array.from
method is not supported by Internet Explorer versions 6-11. If you need to support the browser, use the for loop approach instead.