Create copy of multi-dimensional array, not reference - JavaScript [duplicate]
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.
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;
}