I was working on the last challenge of the JS data structures and algorithm course and wanted to copy an array of arrays without modifying the original array. I found out that I have to take care of each nested array so that when I make some changes on the “copied” arrays, the original arrays won’t change.
Is there a method easier than the one I used to copy an array of arrays without worrying about the nested arrays.
let arr0 = [[1],[2],[3]]
let arr1 = [[1],[2],[3]]
let badClone = arr0.slice()
badClone.map(elem=>elem.push(0))
console.log(arr0, "original array")
console.log(badClone, "bad clone array")
let goodClone = arr1.map(x=>x.slice())
goodClone.map(elem=>elem.push(0))
console.log(arr1, "original array")
console.log(goodClone, "good clone")