2

At first I thought arr.slice(0) was doing a deep unreferenced copy, but it is actually doing just a shallow unreferenced copy, so if the array contains nested arrays, they are still referenced:

var a = [1,2]
var b = [3,4]
var c = [a,b]
var d = c.slice(0)
d[0] === a       // true, which means it is the /same/ object
d[0][0] = "Hi!"
a                // ["Hi!", 2]

(example source)

The solution on the links provided is fairly easy when you know the structure of the array (just .slice(0)ing again the nested arrays will do the trick), but it gets complicated if you don't know how the structure of the nested arrays is.

My first idea is to loop on the whole thing, on all levels, until it fails to find an array object.

  • Is this approach acceptable?
  • Are there some built-in functions that I am missing?

I just can't believe I need to do all that for just copying a silly array

2
  • I'm not sure of your language (javascript?), but often general deep copy problems are overcome using a serialization / deserialization cycle, or using reflection. Commented Jun 5, 2012 at 4:50
  • @nonnb yes, sorry about that (updated) Commented Jun 5, 2012 at 4:53

1 Answer 1

6

Like nonnb suggests, a serializations / deserialization cycle will result in a deep copy. You could do it like this:

//a is some array with arbitrary levels of nesting.
var c = JSON.parse(JSON.stringify(a));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.