Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  101] [ 7]  / answers: 1 / hits: 80004  / 12 Years ago, fri, december 7, 2012, 12:00:00

This is also referred to as "deep copying", which I've found some articles on. Closest seems to be this one but it's for jQuery - I'm trying to do this without a library.


I've also seen, in two places, that it's possible to do something like:


arr2 = JSON.decode(JSON.encode(arr1));

But that's apparently inefficient. It's also possible to loop and copy each value individually, and recurs through all the arrays. That seems tiring and inefficient as well.


So what's the most efficient, non-library way to copy a JavaScript multi-dimensional array [[a],[b],[c]]? I am completely happy with a "non-IE" method if necessary.


Thanks!


More From » arrays

 Answers
2

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.


[#81565] Wednesday, December 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriellagiselc

Total Points: 654
Total Questions: 99
Total Answers: 106

Location: Burkina Faso
Member since Thu, Dec 23, 2021
3 Years ago
;