Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

matrix[0][0] = 1;

console.log(matrix);

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading