Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading