1

I get strange results in my code.

function myFunction() {
  var arrT = new Array(2)
  arrT.fill('-');
  var arrR = new Array(4);
  arrR.fill(arrT);



  console.log(arrR); // returns [ [ '-', '-' ], [ '-', '-' ], [ '-', '-' ], [ '-', '-' ] ]
  arrR[0][1]='xxx'
  console.log(arrR); // returns [ [ '-', 'xxx' ], [ '-', 'xxx' ], [ '-', 'xxx' ], [ '-', 'xxx' ] ]

}

I need a prefilled 2D-array (here I define it fixed but normally the dimension is calculated) I thought I use the fill method and it seemed to work fine. but when I try to put a value in a cell, all rows are filled.

What i'm doing wrong? I expected to have [ [ '-', 'xxx' ], [ '-', '-' ], [ '-', '-' ], [ '-', '-' ] ]

Many thanks in advance,

Filip

TheMaster
  • 45,448
  • 6
  • 62
  • 85
FilMar
  • 11
  • 3
  • 1
    Related: [Array.prototype.fill() with object passes reference and not new instance](https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance) – `.fill()` only copies the primitive value. With `.fill(arrT)`, the primitive is an object reference. So, `arrR` is filled with 4 references all pointing to the same array object. You'll have to create the copies of the array yourself (e.g. `arrT.slice()`). – Jonathan Lonowski May 14 '20 at 17:58

1 Answers1

1

If you fill with array arrR with array arrT, all elements of arrR will be arrT and not a copy of array arrT. Use .map with .slice() to make a copy:

  var arrT = new Array(2)
  arrT.fill('-');
  var arrR = new Array(4).fill(null).map(_=>arrT.slice());



  console.log(arrR); // returns [ [ '-', '-' ], [ '-', '-' ], [ '-', '-' ], [ '-', '-' ] ]
  arrR[0][1]='xxx'
  console.log(arrR); // returns [ [ '-', 'xxx' ], [ '-', '-' ], [ '-', '-' ], [ '-', '-' ] ]
TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • Thanks, but I used a simple loop as it should be faster than the map-slice solution (stated in the related question). Greetings, – FilMar May 22 '20 at 16:54