Skip to main content
xenoveritas.org

Main navigation

  • Categories
  • Home
  • Links
  • Name Generator
  • Scramble
User account menu
  • Log in

Breadcrumb

  1. Home

The Correct Way to Clone Javascript Arrays

By Xenoveritas, 24 February, 2009
Topics
Web

Anonymous (not verified)

15 years 3 months ago

What about an array of object?

Would 'slice' work with an array of objects?
  • Reply

Xenoveritas

15 years 3 months ago

In reply to What about an array of object? by Anonymous (not verified)

Everything is an object in JavaScript

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

  • Reply

Anonymous (not verified)

15 years 2 months ago

In reply to Everything is an object in JavaScript by Xenoveritas

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

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

  • Reply

Xenoveritas

15 years 2 months ago

In reply to Wrong. in that way objects will be passed by reference, not clon by Anonymous (not verified)

So you really mean "deep copy"

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.

  • Reply

Anonymous (not verified)

14 years 7 months ago

In reply to Wrong. in that way objects will be passed by reference, not clon by Anonymous (not verified)

Object cloning

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

  • Reply

Xenoveritas

14 years 6 months ago

In reply to Object cloning by Anonymous (not verified)

Same caveat as below

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.

  • Reply

Anonymous (not verified)

12 years 11 months ago

Exactly what I needed, thanks!!

Exactly what I needed, thanks!!

  • Reply

James (not verified)

12 years 8 months ago

Thanks xeno

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

  • Reply

Abram Clark (not verified)

12 years 4 months ago

Array duplication

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

  • Reply

Xenoveritas

12 years 4 months ago

In reply to Array duplication by Abram Clark (not verified)

Whoops

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

  • Reply

Sam Keddy (not verified)

9 years 4 months ago

Thanks!

Thanks! Simple and dumb.

  • Reply
  • Add new comment

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);

Current Games

I'm currently playing:

  • Final Fantasy XIV: Endwalker

I intend to maybe get around to finishing:

  • Literally anything else

Video Games Section

Thought for the Moment

I never have thoughts any more.

Old Thoughts

Has the LHC Destroyed the Earth?

  • Create new account
  • Reset your password
RSS feed
Powered by Drupal