Home > other >  How to assign value in one cell in 2D array in Javascript
How to assign value in one cell in 2D array in Javascript

Time:02-02

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??

CodePudding user response:

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)

CodePudding user response:

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)

  • Related