-4

I have a 2d array:

let arr = [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]

When I try to update the 1st sub array in the 2nd position with:

arr[0][1] = 4

The output is:

[ [ 0, 4, 0, 0 ], [ 0, 4, 0, 0 ], [ 0, 4, 0, 0 ], [ 0, 4, 0, 0 ] ]

Why are all of the sub arrays updating?

The full code is:

let arr = [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
arr[0][1] = 4
console.log(arr)
imvain2
  • 15,480
  • 1
  • 16
  • 21
Dshiz
  • 3,099
  • 3
  • 26
  • 53
  • 1
    Using the snippet of your code, it is working. – imvain2 May 27 '22 at 19:53
  • you probably have referenced the same array over all places – cmgchess May 27 '22 at 19:53
  • Strange! Thanks for the 2nd set of eyes. – Dshiz May 27 '22 at 19:58
  • Duplicate: [Modifying one index of multidementional array causes every other child array to mutate?](https://stackoverflow.com/questions/64381748/modifying-one-index-of-multidementional-array-causes-every-other-child-array-to). For 13 years of answers of how to avoid the problem see: [How can I create a two dimensional array in JavaScript?](https://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript) – pilchard May 27 '22 at 20:52

1 Answers1

0

You most likely created the array wrongly. Your 2d array has as it's elements a reference to the same array 4 times.

Here is an example:

const array2d = new Array(4).fill([0,0,0,0]);

console.log(JSON.stringify(array2d));
array2d[1][1] = 1;
console.log(JSON.stringify(array2d));

While the array is of length 4, each of its members is replaced with the same array. On the other hand, mapping it instead would give a different result:

const array2d = Array.from({length: 4}, () => [0,0,0,0])

console.log(JSON.stringify(array2d));
array2d[1][1] = 1;
console.log(JSON.stringify(array2d));
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30