104

This is also referred to as "deep copying", which I've found some articles on. Closest seems to be this one but it's for jQuery - I'm trying to do this without a library.

I've also seen, in two places, that it's possible to do something like:

arr2 = JSON.decode(JSON.encode(arr1));

But that's apparently inefficient. It's also possible to loop and copy each value individually, and recurs through all the arrays. That seems tiring and inefficient as well.

So what's the most efficient, non-library way to copy a JavaScript multi-dimensional array [[a],[b],[c]]? I am completely happy with a "non-IE" method if necessary.

Thanks!

17
  • How efficient do you need it to be? Are you doing this over and over again in the client (or is this server side like Node)? The JSON stringify -> parse method is very slick even if not the most efficient. Dec 7, 2012 at 3:32
  • 1
    ...also any circular references to deal with? Dec 7, 2012 at 3:39
  • 1
    I would be sure to benchmark alternatives against json decode+encode. It may seem lame to make strings only to decode them, but it's done in native optimized code- and in the end that may make it faster.
    – goat
    Dec 7, 2012 at 3:44
  • 1
    @RandyHall: Ah, I think I understand. If you're only really dealing with them one level deep at any given time, and if they're actual Arrays, then I'd just iterate the current Array and and build a new one using .slice() on its nested Arrays. It'll be extremely fast. Dec 7, 2012 at 4:02
  • 1
    If you are not dealing with objects as elements (or are not interested in copying them), you can go: matrix.map((row) => [...row]); Aug 29, 2017 at 10:38

5 Answers 5

126

Since it sounds like you're dealing with an Array of Arrays to some unknown level of depth, but you only need to deal with them at one level deep at any given time, then it's going to be simple and fast to use .slice().

var newArray = [];

for (var i = 0; i < currentArray.length; i++)
    newArray[i] = currentArray[i].slice();

Or using .map() instead of the for loop:

var newArray = currentArray.map(function(arr) {
    return arr.slice();
});

So this iterates the current Array, and builds a new Array of shallow copies of the nested Arrays. Then when you go to the next level of depth, you'd do the same thing.

Of course if there's a mixture of Arrays and other data, you'll want to test what it is before you slice.

7
  • I guess that map with its extra function invocations is much slower in the most browsers, though it could be optimized by inlining and then might perform better.
    – Bergi
    Dec 7, 2012 at 4:15
  • @Bergi: Yeah, the map version will take a small hit, but it's nice and clean. Dec 7, 2012 at 4:16
  • 2
    Wow, the map is really clean
    – Dan Tang
    Jun 1, 2014 at 10:45
  • 7
    nowadays you can do es6 shorthand making it even more concise. var newArray = currentArray.map(arr => arr.slice()); Nov 22, 2018 at 2:51
  • 3
    This is NOT "deep" cloning!! - only the 2nd level deep gets copied by value. All the other, deeper levels are still copied by reference and will still change if the original object/array changes. If you want a thoroughly cloned object, JSON parsing is a much safer bet.
    – techexpert
    Jan 30, 2020 at 17:02
27

I'm not sure how much better JSON.stringify and JSON.parse than encode and decode, but you could try:

JSON.parse(JSON.stringify(array));

Something else I found (although I'd modify it a little):

http://www.xenoveritas.org/blog/xeno/the-correct-way-to-clone-javascript-arrays

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;
}
10
  • The downside to both of these methods is that they don't handle self-referential cycles - something that may or may not be important (not sure what the JSON version will do with it, but the second example will infinitely loop)
    – Jeff
    Dec 7, 2012 at 3:43
  • 1
    var x = {}; x.y = x; will hit the else statement every time deepCopy is called, and the JSON just plain can't handle self-references - it's innately tree-based
    – Jeff
    Dec 7, 2012 at 3:51
  • 1
    What is r.prototype = obj.prototype; supposed to do? Seems very wrong to me
    – Bergi
    Dec 7, 2012 at 3:54
  • 1
    @ RandyHall, Jeff: No, it does not. It just creates a property named prototype. This does not set inheritance, as __proto__ would do. Proper way: Object.create(Object.getPrototypeOf(obj)); as in @Danny's answer
    – Bergi
    Dec 7, 2012 at 4:02
  • 1
    @Bergi Yeah, I won't lie, I copied and pasted from the link I provided without thinking. I started looking at the code and realized I would change several things (yet I overlooked the prototype part). I wish I understood more about prototypes and constructors, to understand more, but thanks for the right way to copy the prototype.
    – Ian
    Dec 7, 2012 at 4:18
6

As you asked for performance, I guess you also would go with a non-generic solution. To copy a multi-dimensional array with a known number of levels, you should go with the easiest solution, some nested for-loops. For your two-dimensional array, it simply would look like this:

var len = arr.length,
    copy = new Array(len); // boost in Safari
for (var i=0; i<len; ++i)
    copy[i] = arr[i].slice(0);

To extend to higher-dimensional arrays, either use recursion or nested for loops!

The native slice method is more efficient than a custom for loop, yet it does not create deep copies, so we can use it only at the lowest level.

3

Any recursive algorithm that doesn't visit the same node twice will be about as efficient as you get with javascript (at least in a browser) - in certain situations in other languages you might get away with copying chucks of memory, but javascript obviously doesn't have that ability.

I'd suggest finding someone who's already done it and using their implementation to make sure you get it right - it only needs to be defined once.

0

You could create a copy of multi-dimensional array in JavaScript by using modern way structuredClone:

var arr1 = [[1,2],[3,4],[5,6]];
var arr2 = structuredClone(arr1); //copy arr1
arr2.push([7,8]);

console.log(arr1); //[[1,2],[3,4],[5,6]]
console.log(arr2); //[[1,2],[3,4],[5,6],[7,8]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.