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.