64

This is my code :

var a=[1,2,3]
b=$.clone(a)
alert(b)

Doesn't jQuery have a 'clone' method? How can I clone an array using jQuery?

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
zjm1126
  • 34,604
  • 53
  • 121
  • 166
  • For Multidimensional Array cloning see - http://stackoverflow.com/questions/2294703/multidimensional-array-cloning-using-javascript – vsync May 21 '11 at 09:57
  • Yes. jQuery has a clone method, and also extend with the deep parameter set to true. See http://api.jquery.com/clone/ and http://api.jquery.com/jquery.extend/ The quick and dirty option for small amounts of data is to use JSON.parse(JSON.stringify(original)). For large amounts of data, maybe you shouldn't be cloning?! – podperson Apr 23 '14 at 18:11
  • use spread operator – zloctb Dec 18 '17 at 08:43

8 Answers8

166

Just use Array.prototype.slice.

a = [1];
b = a.slice();

JSFiddle - http://jsfiddle.net/neoswf/ebuk5/

dwitvliet
  • 7,242
  • 7
  • 36
  • 62
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • 1
    This is synonymous with `slice(0)` ? – Peter Ajtai Sep 23 '10 at 04:47
  • 7
    Thanks meder. ....... The only thing to watch out for, is that Arrays are objects, so you can attach properties and methods... like `var a=[1,2,3]; a.foo = function() { alert(this); };` With `slice()` any attached properties and methods aren't copied, so you couldn't do `b.foo()`... I only bring it up, since jQuery's `.clone()` does include a deep copy option. For example: http://jsfiddle.net/B2LQL/ .......... But this is pretty much a corner case in the context of this question. – Peter Ajtai Sep 23 '10 at 19:02
  • I guess my testing code was totally wrong. I uploaded a fiddle and it's working allright http://jsfiddle.net/neoswf/ebuk5/. It's definitions also pointing out that it returns a copy, and not a reference. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice. I editted the your answer and added the fiddle to there. – neoswf Jul 18 '12 at 13:14
  • 12
    Just watch out: This does a *shallow* copy. Not a deep copy. So any objects in the array are not copied, they are simply referenced. – Ariel Jul 01 '13 at 03:57
  • @Ariel, so how do you do a deep copy? – Arman Bimatov Sep 29 '13 at 01:10
  • @ArmanBimatov Sorry, I don't remember what I did. I think I just used an object instead. See: http://forum.jquery.com/topic/jquery-extend-modifies-but-not-replaces-array-properties-on-deep-copy – Ariel Sep 29 '13 at 05:14
  • @Arman See the stringify option below. It's ugly but it works. – podperson Apr 23 '14 at 18:08
11

What about the jQuery.merge ?

copy = $.merge([], a);
viral
  • 3,724
  • 1
  • 18
  • 32
astgtciv
  • 720
  • 5
  • 15
  • 1
    This also does a shallow copy, and therefore is equivalent to the accepted answer. – rych Oct 29 '13 at 22:16
  • 1
    @rych This is not equivalent, as it also works on array-like objects that don't have a .slice method (eg. NamedNodeMap). – janek37 Apr 11 '17 at 15:25
7

This is how i've done it :

var newArray = JSON.parse(JSON.stringify(orgArray));

this will create a new deep copy not related to the first one (not a shallow copy).

also this obviously will not clone events and functions, but the good thing you can do it in one line and it can be used for any king of object (arrays, strings, numbers, objects ...)

Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
  • 1
    This is obviously not the right option for a big, complex structure, but it's a pretty nice one-liner, and actually the approach I ended up taking. – podperson Apr 23 '14 at 18:07
7

Change

b=$.clone(a) to b=$(this).clone(a) but it some time dont work

but is reported

http://www.fusioncube.net/index.php/jquery-clone-bug-in-internet-explorer

Solution you use simple inbuilt clone function of javascript

var a=[1,2,3];
b=clone(a);
alert(b);

function clone(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;
    var temp = obj.constructor();
    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}

-ConroyP

A great alternative is

 // Shallow copy
  var b = jQuery.extend({}, a);

  // Deep copy
  var b = jQuery.extend(true, {}, a);

-John Resig

Check similar post

Community
  • 1
  • 1
Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34
2

ES6 Please use spread

let arrayCopy = [...myArray];
zloctb
  • 10,592
  • 8
  • 70
  • 89
1

try

if (!Array.prototype.clone) {
    Array.prototype.clone = function () {
        var arr1 = new Array();
        for (var property in this) {
            arr1[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]
        }
        return arr1;
    }​
}

use as

var a = [1, 2, 3]
b = a;
a.push(4)
alert(b); // alerts [1,2,3,4]
//---------------///
var a = [1, 2, 3]
b = a.clone();
a.push(4)
alert(b); // alerts [1,2,3]​
Arturs
  • 1,258
  • 5
  • 21
  • 28
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
1

Another option is to use Array.concat:

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

var a=[1,2,3]
b=JSON.parse(JSON.stringify(a));
document.getElementById("demo").innerHTML = b;
<p id="demo"></p>