Is there a more efficient method to create an m×n 2d array in JavaScript or TypeScript, rather than using nested arrays?
arr = [[0, 0], [0, 0]]
An alternative approach is:
arr = new Array(m).fill(new Array(n).fill(0))
However, this results in all rows being the same array:
arr[1][2] = 5
console.table(arr)
(index) | 0 | 1 | 2 |
---|---|---|---|
0 | 0 | 0 | 5 |
0 | 0 | 0 | 5 |
To avoid this issue, you can use the following syntax:
arr = [...new Array(2)].map(() => new Array(3).fill(0))
While functional, some might view this as inelegant. Are there better options in JavaScript or TypeScript for creating 2d arrays?