Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing and filling multi dimension array in javascript

How do we initialize and create new multi dimension array?

Let's imagine if I want to initialize a 4x4 multi dimension array and fill it with 0's

Ideally, in 2D arrays, we would do

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

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

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

I'm trying to solve few algorithm problems and this requires me creating a new multi dimension array and going through them (Island problem etc)

Please advise.

EDIT:

Another solution I found:

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

like image 811
TechnoCorner Avatar asked Aug 22 '17 18:08

TechnoCorner


People also ask

How do you fill an array in JavaScript?

fill() The fill() method changes all elements in an array to a static value, from a start index (default 0 ) to an end index (default array. length ). It returns the modified array.

How multidimensional array works in JavaScript?

Multidimensional arrays are not directly provided in JavaScript. If we want to use anything which acts as a multidimensional array then we need to create a multidimensional array by using another one-dimensional array. So multidimensional arrays in JavaScript is known as arrays inside another array.


1 Answers

To get an independent filled array, you could use Array.from and map a new array with mapped 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; }
like image 139
Nina Scholz Avatar answered Oct 13 '22 13:10

Nina Scholz