0

I'm trying to copy an 2d array, but every time I change the value of the copied array, it changes the original one too.

Original Array

 board = [
        [0,1,0],
        [0,0,1],
        [1,1,1],
        [0,0,0]
      ];
let ans = board.slice();
    
    for(let i=0; i<board.length; i++){
        for(let j=0; j<board[i].length; j++){
            let neighbors = checkCell(board, i, j);
            if(board[i][j] === 1) {
                ans[i][j] = (neighbors === 2 || neighbors === 3 ? 1 : 0);
            } else {
                ans[i][j] = (neighbors === 3 ? 1 : 0);
            }
        }
    }

checkCell() is just a method which returns 1 or 0. My problem is that when I set a value to ans, it also changes the original board array. I tried to copy using and = [...board]; and got the same problem.

1

2 Answers 2

3

When you copy via .slice or [...] it performs a shallow copy, which means the outer array is copied but the inner arrays aren't. You can individually copy each element:

let ans = board.map(v => v.slice()); // copies every 1d array
Sign up to request clarification or add additional context in comments.

Comments

1

This is happening because the slice() method returns a shallow copy of elements and the way elements are copied is using the references, i.e. both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Use slice only when you want a shallow copy of the parent array to produce some other outputs.

You can read more here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.