Question

This simple code works for arrays of one dimension but not for multidimensional ones:

var a=[[0,0,0],[0,0,0],[0,0,0]];
var b=a.slice(0);

a[0][0]=2;

alert(b[0][0]);//Should display 0, but displays 2

http://jsfiddle.net/e2vFk/3

How can I duplicate a multidimensional array?

EDIT: For this example, the dimension is 2, but the dimension of my real array is 4

Was it helpful?

Solution

Here's a generic solution, which will work for any depth, and assumes that your Arrays are actually Arrays, and not Array-like objects.

function clone(arr) {
    arr = arr.slice()
    for (var i = 0; i < arr.length; i++)
        if (Array.isArray(arr[i]))
            arr[i] = clone(arr[i])
    return arr
}

The Array.isArray method can be shimmed if needed for older browsers.

if (!Array.isArray) {
    Array.isArray = function(arr) {
        return Object.prototype.toString.call(arr) === "[object Array]"
    }
}

function clone(arr) {
    return arr.map(function(item) {
        if (Array.isArray(item))
            return clone(item)
        return item
    })
}

Here's a solution that uses .map() instead.

OTHER TIPS

 var b=a.map(function(arr) { return arr.slice(); });

Easiest way to make a clone is

function clone(array){
   return JSON.parse(JSON.stringify(array));
}

Works for everything/any dimension except if you have functions and circular variables.

you are only duplicating the references.. use a loop

var a=[[0,0,0],[0,0,0],[0,0,0]];
var b= new Array()
for(i=0;i<a.length;i++)
    b[i]=a[i].slice(0);



a[0][0] = 2

alert(b[0][0]);
alert(a[0][0]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top