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?

3
  • For Multidimensional Array cloning see - stackoverflow.com/questions/2294703/… Commented May 21, 2011 at 9:57
  • Yes. jQuery has a clone method, and also extend with the deep parameter set to true. See api.jquery.com/clone and 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?! Commented Apr 23, 2014 at 18:11
  • use spread operator Commented Dec 18, 2017 at 8:43

8 Answers 8

166

Just use Array.prototype.slice.

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

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

Sign up to request clarification or add additional context in comments.

7 Comments

This is synonymous with slice(0) ?
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: jsfiddle.net/B2LQL .......... But this is pretty much a corner case in the context of this question.
I guess my testing code was totally wrong. I uploaded a fiddle and it's working allright jsfiddle.net/neoswf/ebuk5. It's definitions also pointing out that it returns a copy, and not a reference. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…. I editted the your answer and added the fiddle to there.
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, so how do you do a deep copy?
|
11

What about the jQuery.merge ?

copy = $.merge([], a);

2 Comments

This also does a shallow copy, and therefore is equivalent to the accepted answer.
@rych This is not equivalent, as it also works on array-like objects that don't have a .slice method (eg. NamedNodeMap).
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

3 Comments

Japan- Extend is meant for Objects. Ur first func was also meant for Object.
Extend works great for an array too, just change empty object {} into an empty array [].
When I used extend() and passed in {}, it didn't work right. It might work if I pass in [] instead.
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 ...)

1 Comment

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.
2

ES6 Please use spread

let arrayCopy = [...myArray];

Comments

1

Another option is to use Array.concat:

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

1 Comment

Basically the same problem as using slice.
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]​

2 Comments

This is just in case you've attached other properties to the array in addition to the values in the array? (as opposed to just using slice(0))?
@Peter - slice(0) is good. I'm just showing another way of solving it. ;)
0

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

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.