tags:

views:

43

answers:

1

Hi, I want to make a clone of multidimensional Array so that i can play arround with the clone array without affecting main Array.i m using following function to do so,

Array.prototype.clone = function () { 
        var newArray = new Array(this.length);
          for(var i=0; i < this.length; i++ ){
             newArray[i] = this[i];
        }
      return newArray;
    };

But problem which is since it is using array prototype so it will clone my all array.so can any body tell me what is the best way of doing this.

+2  A: 

You need to use recursion

var a = [1,2,[3,4,[5,6]]];

Array.prototype.clone = function() {
    var arr = [];
    for( var i = 0; i < this.length; i++ ) {
//      if( this[i].constructor == this.constructor ) {
        if( this[i].clone ) {
            //recursion
            arr[i] = this[i].clone();
            break;
        }
        arr[i] = this[i];
    }
    return arr;
}

var b = a.clone()

console.log(a);
console.log(b);

b[2][0] = 'a';

console.log(a);
console.log(b);

/*
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, ["a", 4, [5, 6]]]
*/

Any other objects in the original array will be copied by reference though

meouw
You could check for the presence of a `clone` method on each object in the array, and call it to clone the object if present. This will handle the recursion of arrays and also allow any other objects with clone methods to be deep-copied as well.
Daniel Earwicker
Thanks Earwicker, that's a good point, I'll amend my answer
meouw