By | November 4, 2017

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!

Believe it or not, there are reasons we use JavaScript frameworks outside of animations and those sexy accordions that people can’t do without. The further you get into high-powered JavaScript applications (assuming you’re creating true web applications, not websites), the more the need for basic JavaScript functionalities; i.e. JavaScript utilities that have nothing to do with DOM. One of those basic utilities is the ability to clone an array. Quite often I see developers iterating over array items to create their clone; in reality, cloning an array can be as easy as a slice!

Leave a Reply

Your email address will not be published. Required fields are marked *