Daily Archives: December 5, 2011

Cloning an array with JavaScript

I had a need to clone an array with JavaScript. There appears to be a number of different ways to do it, including writing your own function. All of these solutions below will just create a reference to the original array:

var newArray = myArray.slice(0);
var newArray = myArray.concat([]);
var newArray = clone(myArray);

A popular answer using jQuery is the following:

var newArray = jQuery.extend(true, {}, myArray);

However, this solution will return an object and you cannot get the length of an object like you can an array.

To return an array, we change the curly braces to square brackets like so:

var newArray = jQuery.extend(true, [], myArray);

This is the solution that works.