Search code examples
javascriptarraysclone

Clone a 4D multidimensional array


I know this question has been asked before but all of the answers assume the array is a 2D array and only go one level deep.

I have a 4D array and have tried some of the solutions here and did not get the result. Here's my array:

Image of array

I tried this answer from this question but this only goes one level deep. How do I make it work with a 4D array?

var newArray = [];
for (var i = 0; i < currentArray.length; i++)
newArray[i] = currentArray[i].slice();

Solution

  • You could use a simple recursive function that replaces arrays with copies after recursively handling its values:

    function deepCopy(value) {
        if (Array.isArray(value)) {
            return value.map(deepCopy);
        }
        return value;
    }
    
    const data = [[[0]]];
    const copy = deepCopy(data);
    data[0][0][0] = 123;
    console.log(data);
    console.log(copy);

    Actually looking at the bottom answers of that question, there are already (more complicated) deep copy functions present, such as this one. You can still use mine if you want a very simply only-deep-copies-arrays version of course.