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));
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With