1

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!

James Lee
  • 67
  • 5
  • 3
    you already know you have to use something like `.slice` for 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 be `b = JSON.parse(JSON.stringify(a))` – Jaromanda X Mar 08 '20 at 20:28
  • I see... I wish I didn't have to use the slow JSON here haha.. Thank you very much for your help – James Lee Mar 08 '20 at 20:40
  • @JamesLee `b = a.map(x => x.slice());` – Đinh Carabus Mar 08 '20 at 21:15

2 Answers2

1

If you know you are only copying 2D arrays you could use a function like the following and avoid using JSON:

function copy2D(array){
  result = []
  array.forEach((subArray) => {
    result.push(subArray.slice())
  })
  return result
}
Someone
  • 800
  • 1
  • 7
  • 25
1

One way would be by using map combined with the spread operator. This would be the easiest approach if you can assume that you have a 2D array only

const a = [[1, 2], [3, 4]]
const b= a.map(item => ([...item]))

b[0][0]= "abc"
console.log('a:', a, 'b: ', b)
r4pt0s
  • 79
  • 10