The Correct Way to Clone Javascript Arrays

I couldn't remember how to clone arrays in JavaScript, so I did a quick search for the answer.

I found some, uh, not-so-great answers, mainly involving writing custom copy functions that iterated over every item in the array to copy it.

Turns out there already exists a method in JavaScript 1.2+ (in other words, in all major browsers) to clone arrays. It's called, helpfully enough, slice(begin[,end]).

It returns a copy of the given slice of the array.

Or it can return the entire array.

So copying an array in JavaScript is simply:

var clone = originalArray.slice(0);

That's it. Simple. No need to iterate over the array and copy each element individually.

If you really want a clone method:

Array.prototype.clone = function() { return this.slice(0); }

Here's a simple example:

var a = [ 'apple', 'orange', 'grape' ];
b = a.slice(0);
b[0] = 'cola';
document.writeln("a=" + a + "<br>");
document.writeln("b=" + b);

Topics: 

Comments

Would 'slice' work with an array of objects?

Considering that everything is an object in JavaScript, I would have to answer yes.

Wrong. in that way objects will be passed by reference, not cloned

So what you're really asking is there an easy way to do a deep copy. And the answer to that is "no." (Sadly, the answer to "is there a good way to do a deep copy" is also "no" if you ever include any DOM objects.)

However, an array of objects can be cloned. Just remember that it's really an array of object references, and you're creating a copy of the array of object references.

Otherwise, your best bet for a deep copy is:

function deepCopy(obj) {
  if (typeof obj == 'object') {
    if (isArray(obj)) {
      var l = obj.length;
      var r = new Array(l);
      for (var i = 0; i < l; i++) {
        r[i] = deepCopy(obj[i]);
      }
      return r;
    } else {
      var r = {};
      r.prototype = obj.prototype;
      for (var k in obj) {
        r[k] = deepCopy(obj[k]);
      }
      return r;
    }
  }
  return obj;
}

var ARRAY_PROPS = {
  length: 'number',
  sort: 'function',
  slice: 'function',
  splice: 'function'
};

/**
 * Determining if something is an array in JavaScript
 * is error-prone at best.
 */
function isArray(obj) {
  if (obj instanceof Array)
    return true;
  // Otherwise, guess:
  for (var k in ARRAY_PROPS) {
    if (!(k in obj && typeof obj[k] == ARRAY_PROPS[k]))
      return false;
  }
  return true;
}

Note that this will only really work on JSON objects. It sort of works on regular JavaScript objects solely because the functions from the prototype will show up in the iteration - but the cloned object won't be an "instanceof" object.

There's no real way around that because there's no JavaScript-standard way of getting the prototype from the original object.

nowadays you can clone objects with
CLONEDOLLY = JSON.parse(JSON.stringify(DOLLY));

This has the same caveat as the large blurb below: you're not really cloning the object, you're creating a new object with the same properties.

This also won't clone the prototype or any functions on the object. It works for JSON objects, but nothing else.

Exactly what I needed, thanks!!

Absolutely perfect.... wish this site was the first hit by google. Your comment conversation answered my problem, and gave me some background understanding

There's an even simpler option, helpfully called Array.concat

This comment came so close to getting accidentally deleted while clearing comment span. In that I had to actually restore it from backup.