views:

3526

answers:

5

Hello, I need to copy an (ordered, not associative) array of objects. I'm using jquery. I initially tried

jquery.extend({}, myArray)

but, naturally, this gives me back an object, where I need an array (really love jquery.extend, by the way). So, what's the best way to copy an array?

+4  A: 

test = $.extend([], [['a', ['c']], 'b'])

That should do it for you.

geowa4
+7  A: 

Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.

var foo = ['a','b','c','d','e'];
var bar = foo.slice();

now foo and bar are 5 member arrays of 'a','b','c','d','e'

of course bar is a copy, not a reference... so if you did this next...

bar.push('f');
alert('foo:' + foo.join(', '));
alert('bar:' + bar.join(', '));

you would now get:

foo:a, b, c, d, e
bar:a, b, c, d, e, f
scunliffe
+1  A: 

I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.

http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/

Diodeus
Thanks, was looking for a catch-all clone (sometimes have an object, sometimes an array of objects).
Matt Gardner
+1  A: 

Everything in JavaScript is pass by reference, so if you want a true deep copy of the objects in the array, the best method I can think of is to serialize the entire array to JSON and then de-serialize it back.

+18  A: 

Since Array.slice() does not do deep copying, it is not suitable for multidimensional arrays:

var a =[[1], [2], [3]];
var b = a.slice();

b.shift().shift();
// a is now [[], [2], [3]]

jQuery's extend method does the trick, when a true value is passed as the initial argument:

var a =[[1], [2], [3]];
var b = $.extend(true, [], a);

b.shift().shift();
// a is still [[1], [2], [3]]
Noah Sussman
Thanks Noah. Looks like my biggest problem was that I was giving $.extend and object as its first argument, not an array.
morgancodes