karim_mo
karim_mo

Reputation: 147

Mutating an array

I want to change only the first column in the firs row but it doesn't work.

wanted output is [[1,0],[0,0]], but what I get is[[1,0],[1,0]]

I want to know why this happens and what is the solution if I want to make a change in a different index ?

let matrix = [];
let row = [0, 0];
for (i = 0; i < 2; i++) {
  matrix.push(row);
}

matrix[0][0] = 1;

console.log(matrix);

Upvotes: 0

Views: 113

Answers (3)

brk
brk

Reputation: 50291

The variable row which is pushed to the matrix array points to the same memory location. So any update on this variable will be reflected everywhere. You need to create a new one every time you push it

let matrix = [];
for (let i = 0; i < 2; i++) {
  let row = [0, 0];
  matrix.push(row);
}
matrix[0][0] = 1;
console.log(matrix);

Upvotes: 2

user17487781
user17487781

Reputation:

Either just push a new array:

matrix.push([0,0])

Or you can use the spread operator:

matrix.push([...row])

Upvotes: 0

Taxel
Taxel

Reputation: 4197

The problem is, that you are pushing the same object (row) into the matrix twice. Make a copy of row for example with the spread operator, or Array.slice():

let matrix = [];
let row = [0, 0];
for (i = 0; i < 2; i++) {
  matrix.push([...row]);
}

matrix[0][0] = 1;

console.log(matrix);

Upvotes: 3

Related Questions