I want to copy an array of arrays at a different allocation.
I know that I can copy an array in the following way:
a = [[1, 2], [3, 4]]
b = a.slice() // this makes sure that a and b are allocated differently in memory
Now if I change something inside b, then of course,
b[0] = 'abc'
console.log(a, b) // expect a = [[1,2], [3,4]] and b = ['abc', [3,4]]
But when I do the below, a gets changed as well...!
b[0][0] = 'abc'
console.log(a, b) // now it gives a = [['abc', 2], [3, 4]] and b = [['abc', 2], [3, 4]]
Why is this happening, and how can I avoid mutating a? Thanks so much!
.slicefor arrays to get a separate copy. Arrays within arrays behave exactly the same. With a multi dimensional array of "primitive values", or even simple objects (like arrays, or objects with no circular references), the simplest method, not covered in the above link would beb = JSON.parse(JSON.stringify(a))b = a.map(x => x.slice());