Create arbitrary size JavaScript/TypeScript 2d array in one line

Advertisements

How would I create an m×n 2d array in JavaScript or TypeScript? Of course, I could create a 2×3 array with:

arr = [[0, 0], [0, 0]]

But the dimensions are given to me in variables m and n. So I can do the following:

arr = new Array(m).fill(new Array(n).fill(0))

But the rows are all the same array:

arr[1][2] = 5
console.table(arr)
(index) 0 1 2
0 0 0 5
0 0 0 5

I only modified the bottom row, but the top row was affected as well. So the following does what I want (each cell is a different memory location):

arr = [...new Array(2)].map(() => new Array(3).fill(0))

This works, but it’s pretty ugly. Does JavaScript or TypeScript have a more appropriate or efficient way to create 2d arrays?

>Solution :

Try using Array.from

let arr = Array.from({length: 3}, () => Array(3).fill(0))

arr[1][2] = 5

console.log(arr)

Leave a ReplyCancel reply