1

Created an array using:

var r = new Array(2).fill(new Array(2).fill(-1))

which looks like this:

[
  [-1 -1]
  [-1 -1]
]

Now want to update any one cell of this 2d array with any value like:

 r[1][0] = "r";

It is updating whole column itself, which look like something like:

[
  [r -1]
  [r -1]
]

How we can make sure only one cell gets updated??

pl2ern4
  • 340
  • 2
  • 10
  • 4
    Does this answer your question? [Array.fill(Array) creates copies by references not by value](https://stackoverflow.com/questions/37949813/array-fillarray-creates-copies-by-references-not-by-value) – Reyno Feb 01 '23 at 20:39

2 Answers2

1

With new Array(2).fill(new Array(2).fill(-1)) you are filling both elements of the outer array with references to the same inner array. That's why both subarrays get updated when you update one element in it. Instead, use Array.map to ensure a new array is generated for each element.

var r = new Array(2).fill(-1).map(_ => new Array(2).fill(-1));
r[1][0] = "r";
console.log(r)
Fractalism
  • 1,231
  • 3
  • 12
1

The issue is that the inner arrays are references to the same array object

You can use Array.from() like this:

const len = { length: 2 }
const r = Array.from(len, () => Array.from(len, () => -1))

r[1][0] = 'r'

console.log(r)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46