Initializing and populating a multidimensional array in javascript

How do we initialize and create a new multidimensional array?

Suppose I want to initialize a 4x4 multidimensional array and fill it with 0

Ideally, in 2D arrays we will do

let oned_array = new Array(10).fill(0); // create an array of size 10 and fill it with 0

How would I do something like [[0,0], [0,0]] (2x2 matrix)

 let matrix = new Array([]).fill(0); 

I am trying to solve several problems with algorithms, and this requires me to create a new multidimensional array and go through them (problem with an island, etc.)

Please inform.

EDIT:

Another solution I found:

Array(2).fill(0).map(_ => Array(2).fill(0));

+5
source share
2 answers

To get an independent populated array, you can use Array.from and map the new array to the displayed values.

 var array = Array.from({ length: 4 }, _ => Array.from({ length: 4 }, _ => 4)); array[0][0] = 0; console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 
+3
source

@NinaScholz 'the answer is much better, as always, but I ended up writing this before seeing this answer, so I decided to post it anyway.

A similar idea, but without using Array.from . It creates a new array with the specified length, fills it with 0, so that it can be iterated, iterate it replaces 0 with a new array of the specified length, filled with the specified value.

 const buildMatrix = (l, h, v) => Array(l).fill(0).map(_ => Array(h).fill(v)); const matrix = buildMatrix(4,4,4); matrix[0][0] = 0; console.log(matrix); 
 .as-console-wrapper { max-height: 100% !important; } 
+2
source

Source: https://habr.com/ru/post/1271120/


All Articles