(Deep) copying an array using jQuery [duplicate]

(Deep) copying an array using jQuery [duplicate]

Possible Duplicate:
What is the most efficient way to clone a JavaScript object?

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?

Solutions/Answers:

Solution 1:

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]]

Note that although I’ve used shift().shift() above, the point is just that b[0][0] contains a pointer to a[0][0] rather than a value.

Likewise delete(b[0][0]) also causes a[0][0] to be deleted and b[0][0]=99 also changes the value of a[0][0] to 99.

jQuery’s extend method does perform a deep copy 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]]

Solution 2:

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

That should do it for you.

Related:  Passing dynamic javascript values using Url.action()

Solution 3:

I realize you’re looking for a “deep” copy of an array, but if you just have a single level array you can use this:

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

Solution 4:

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.

Solution 5:

If you want to use pure JavaScript then try this:

 var arr=["apple","ball","cat","dog"];
 var narr=[];

 for(var i=0;i<arr.length;i++){
     narr.push(arr[i]);
 }
 alert(narr); //output: apple,ball,vat,dog
 narr.push("elephant");
 alert(arr); // output: apple,ball,vat,dog
 alert(narr); // apple,ball,vat,dog,elephant

Solution 6:

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.

Related:  Convert javascript code to c code

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