How to Clone a (Nested) Array in Javascript

The Problem

David Walsh has a quick tutorial on how to clone an array in Javascript:

var clone = myArray.slice( 0 );  

This has an unmentioned danger. If your array contains nested arrays, the "clone" will contain references to the old arrays. Observe:

var original = [ [1] ];  
var cloned = original.slice( 0 ); // "clone" the array

cloned[ 0 ].push( 2 ); // modify the "clone"

console.log( original[ 0 ] ); // Logs [ 1, 2 ] !  

The Solution

Let's write a recursive function to clone an array that could potentially have nested arrays.

function arrayClone( arr ) {

    var i, copy;

    if( Array.isArray( arr ) ) {
        copy = arr.slice( 0 );
        for( i = 0; i < copy.length; i++ ) {
            copy[ i ] = arrayClone( copy[ i ] );
        }
        return copy;
    } else if( typeof arr === 'object' ) {
        throw 'Cannot clone array containing an object!';
    } else {
        return arr;
    }

}

If you have Underscore we can make it even shorter:

function arrayClone( arr ) {  
    if( _.isArray( arr ) ) {
        return _.map( arr, arrayClone );
    } else if( typeof arr === 'object' ) {
        throw 'Cannot clone array containing an object!';
    } else {
        return arr;
    }
}

Other Options

If you need deep cloning of arbitrarily nested objects and / or arrays, the tiny node-clone does a robust job. It will even correctly handle cloning of objects with circular references!

That's It!

If this tip helped you, consider following me on Twitter or buying me a coffee :).

comments powered by Disqus