Home > Net >  Two arrays update together when I only want one to change
Two arrays update together when I only want one to change

Time:12-15

Here is my code:

let rowValues = [];
let gridValues = [];
let testArray = [[1,1,1],[0,0,0],[1,1,1],[0,0,0],[1,1,1]];
let rows = 5;
let cols = 3;

for (let i = 0; i < rows; i  ) {
    rowValues.length = [];

    for (let j = 0; j < cols; j  ) {

        if (testArray[i][j] === 0) {
            rowValues.push(0);
        } else if (testArray[i][j] === 1) {
            rowValues.push(1);
        }
    }
    gridValues.push(rowValues);
}

The problem is that the gridValues array updates with the rowValues array after the first iteration of the first for loop (once i = 1). It's like they become linked and when you update one the other follows suit. What is going on here??

All I want to have happen is build the rowValues array and then push it into the gridValues array to build a 2D array. But when rowValues is cleared at the start of the next iteration, gridValues is cleared too.

CodePudding user response:

gridValues.push(rowValues) inserts a reference of rowValues into gridValues. And since you execute that command 5 times (once for each row), the same reference is inserted 5 times, which explains why the result contains 5 copies of the last row's data [1,1,1]. When you reset the array using rowValues.length = [], the references you've already inserted into gridValues will point to the new value.

You can avoid this problem by replacing line 18 with the following that pushes a copy of the array using the spread syntax:

gridValues.push([...rowValues]);

Also, I'm not sure what you're trying to achieve - perhaps you contrived your example - but if you simply want to clone the array testArray then there's no need for a for loop or .push() at all because you can just use the spread syntax on that:

const testArray = [[1,1,1],[0,0,0],[1,1,1],[0,0,0],[1,1,1]];
const gridValues = [...testArray];

CodePudding user response:

gridValues.push(JSON.parse(JSON.stringify(rowValues))

CodePudding user response:

Change

rowValues.length = [];

to

rowValues = [];

  • Related