function sortMatrixRows(matrix) {
const copy = [...matrix]; // copy of the outer array
copy.forEach(row => row.sort((a, b) => a - b));
return copy;
}
const grid = [[3,1,2],[6,4,5],[9,7,8]];
const sorted = sortMatrixRows(grid);
console.log(sorted[0]); // [1, 2, 3] β
console.log(grid[0]); // [1, 2, 3] β MUTATED! Expected [3, 1, 2]function sortMatrixRows(matrix) {
// Deep copy: spread outer array AND each inner row
return matrix.map(row => [...row].sort((a, b) => a - b));
}
// Alternative: use structuredClone for any depth
function sortMatrixRowsDeep(matrix) {
const copy = structuredClone(matrix);
copy.forEach(row => row.sort((a, b) => a - b));
return copy;
}
const grid = [[3,1,2],[6,4,5],[9,7,8]];
const sorted = sortMatrixRows(grid);
console.log(sorted[0]); // [1, 2, 3] β
console.log(grid[0]); // [3, 1, 2] β unchangedBug: [...matrix] creates a new outer array but the inner row arrays are the SAME references. Sorting a row sorts the original row in grid.
Explanation: Spread is shallow β inner arrays are not copied, just their references. Sort mutates in place, affecting the original. Copy each row individually with [...row] or use structuredClone().
Key Insight: Spread creates a shallow copy of the TOP-LEVEL container. Nested arrays/objects are still shared references. Deep copy nested structures before mutating them.