-1

Suppose I have the following array structure:

let cells = [
  ['foo', 'foo'],
  ['foo', 'foo']
]

And I want to update it so it becomes:

[
  ['bar', 'foo'],
  ['foo', 'foo']
]

I thought this would suffice:

cells[0][0] = 'bar';

But that changes cells[1][0] too, resulting instead in:

[
  ['bar', 'foo'],
  ['bar', 'foo']
]

How do I only change cells[0][0]?

Sajad Torkamani
  • 544
  • 1
  • 7
  • 18
  • 5
    You didn't show the whole picture in your question. Chance is, you first create an array, store it into the variable (with something like `let row = ['foo', 'foo']`, then use something like `let cells = [row, row]`. In this case, you _reuse_ the same object; naturally, when you change its property, all the rows are changed instead. – raina77ow Jun 19 '17 at 19:17

1 Answers1

2

Sounds like in your program, you have an array with two attributes referencing the same object. This would happen in the following code:

let row = ["foo", "foo"]
let cells = [];
cells.push(row);
cells.push(row);

When you do cells.push(row), you don't create a new array which will be pushed to cells, you instead pass the array by reference.

There is now only one array row = ["foo", "foo"], referenced twice by the cells object. By doing cells[0][0] = "bar", I would change the first element of the row object. Since the same object is referenced inside of the cells object twice, it will be the same on both positions.

Depending on your use case, you either want to clone the first array, or create a new array independently on the first array.

For your options of cloning the array, check out this question.

BoltKey
  • 1,994
  • 1
  • 14
  • 26
  • Thanks for the clear explanation! It was indeed a case of the array elements referring to the same object. Thought it would be something silly on my part! – Sajad Torkamani Jun 20 '17 at 10:42