Array.fill (Array) creates copies of non-value links

I am trying to create a 6 by 12 matrix using Array.fill

let m = Array(6).fill(Array(12).fill(0));

While this works, the problem is that the internal arrays are actually referring to the same object Array.

let m = Array(6).fill(Array(12).fill(0));
m[0][0] = 1;
console.log(m[1][0]); // Outputs 1 instead of 0

I wanted (and expected) the meaning to m[1][0]be 0.

How can I make Array.fillcopies fill in by the values ​​of this argument (for example: Array(12).fill(0)- this is an argument in my case) instead of copying by reference?

+4
source share
3 answers

Instead of Array.from () :

Thanks Pranav C Balanin the comments to the proposal for further improvement of this.

let m = Array.from({length: 6}, e => Array(12).fill(0));

m[0][0] = 1;
console.log(m[0][0]); // Expecting 1
console.log(m[0][1]); // Expecting 0
console.log(m[1][0]); // Expecting 0
Run code

( ):

let m = Array.from({length: 6}, e => Array.from({length: 12}, e => 0));
+3

.fill(), .map():

let m = new Array(6).map(function() { return new Array(12); });

edit oh wait, ; .map() . :

let m = new Array(6).fill(null).map(function() { return new Array(12); });
+2

You cannot do this with a method . Instead, iterate over the array and add the newly created array using the for loop. Array#fill

let m = Array(6);
for (var i = 0; i < m.length; i++)
  m[i] = Array(12).fill(0)

m[0][0] = 1;
console.log(m[1][0]);
Run code
+2
source

All Articles