Copying an array of arrays

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()>elem.push(0))
console.log(arr0, "original array")
console.log(badClone, "bad clone array")
let goodClone =>x.slice())>elem.push(0))
console.log(arr1, "original array")
console.log(goodClone, "good clone")

You should not use a map as if it is a forEach. The purpose of a map is to create a new array from an old array.

Your options are 1) manually do a deep copy, 2) call a library that has a deep copy functionality, or 3) convert back and forth from a JSON.

1 Like

Thanks for the tip about forEach and map.
Can you show me an example for option 2

You’d be looking at something like Lodash: Lodash - Wikipedia

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.