0

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); 
3
  • 2
    matrix.push(row); This is adding the same object over and over. When you change it in 1 place you change it in all the places. Commented Nov 23, 2021 at 14:25
  • Solution is matrix.push([...row]); Commented Nov 23, 2021 at 14:26
  • There's only one "row" reference--if you change it it will change everywhere it's referenced. Commented Nov 23, 2021 at 14:26

3 Answers 3

3

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);

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

Comments

2

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);

Comments

0

Either just push a new array:

matrix.push([0,0]) 

Or you can use the spread operator:

matrix.push([...row]) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.