Multidimensional array cloning using javascript

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

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 the problem is that it uses a massive prototype so that it clones all my arrays. Can any body tell me that this is the best way to do this.

+3
javascript
Feb 19 '10 at 7:30
source share
3 answers

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 source array will be copied by reference, although

+2
Feb 19 '10 at 8:17
source share

vsync is correct, my first answer does not handle var a = [[1,2],[3,4]];
So, the improved version

 var a = [[1,2],[3,4]]; Array.prototype.clone = function() { var arr = this.slice(0); for( var i = 0; i < this.length; i++ ) { if( this[i].clone ) { //recursion arr[i] = this[i].clone(); } } return arr; } var b = a.clone() console.log(a); console.log(b); b[1][0] = 'a'; console.log(a); console.log(b); //[[1, 2], [3, 4]] //[[1, 2], [3, 4]] //[[1, 2], [3, 4]] //[[1, 2], ["a", 4]] 
+10
May 21 '11 at 14:46
source share

I found that this approach is better than meouw:

 var source = [ [1, 2, {c:1}], [3, 4, [5, 'a']] ]; // Create a new method ontop of the "Array" primitive prototype: Array.prototype.clone = function() { function isArr(elm) { return String(elm.constructor).match(/array/i) ? true : false; } function cloner(arr) { var arr2 = arr.slice(0), len = arr2.length; for (var i = 0; i < len; i++) if (isArr(arr2[i])) arr2[i] = cloner(arr2[i]); return arr2; } return cloner(this); } // Clone var copy = source.clone(); // modify copy copy[0][0] = 999; console.dir(source); console.dir('**************'); console.dir(copy); 

Another method that can only work with datasets that have primitives as values ​​( String , Numbers , Objects ):

 var source = [ [1,2, {a:1}], ["a", "b", ["c", 1]] ]; // clone "srouce" Array var copy = JSON.parse(JSON.stringify(source)); // modyfy clone copy[0][0] = 999; // print both arrays console.dir(copy) console.log('***********') console.dir(source) 
+2
May 21 '11 at 13:03
source share



All Articles