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.

myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78
  • Check this out https://stackoverflow.com/questions/45949241/why-cant-i-make-a-copy-of-this-2d-array-in-js-how-can-i-make-a-copy – ABGR Jun 29 '20 at 15:05

2 Answers2

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
Aplet123
  • 33,825
  • 1
  • 29
  • 55
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

Aman-D
  • 71
  • 3