Creating an Array of N Numbers
During a coding test, I wanted to create an array of N numbers and use forEach
.
While I could have used a simple for
or while
loop, I was more comfortable using array methods, so I started searching for a suitable method.
1D Array (Array of N numbers)
- for loop
function createArray(n) {
const result = []
for (let i = 1; i <= n; i++) {
result.push(i)
}
return result
}
- while loop
function createArray(n) {
const result = []
let i = 1
while (i <= n) {
result.push(i)
i++
}
return result
}
- Array.from
//* Recommend
const array = Array.from({ length: n }, (_, i) => i + 1)
- Array.map
const array = Array(n)
.fill()
.map((_, i) => i + 1)
Creating a 2D Array, e.g. [[1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5]]
2 minutes to read