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

1

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.