Question

The nested array is changed even though I work on a clone inside the function. What's the most efficient way to preserve the a array? JSBin here.

var a = [[2,3],[1,5,2],[3,7,2]];
function c(a) {
  var l = a.slice(0);
  console.log('in func, before change',l);
  l[1].splice(1,1);
  console.log('in func, after change',l);
}
console.log('before call', a);
c(a);
console.log('after call',a);
Was it helpful?

Solution

Your code works just fine on a 1 dimensional array:

function c(a) {
  var l = a.slice(0);
  console.log('in func, before change',l);
  l[1] = 17;
  console.log('in func, after change',l);
}

var a = [2,3,1,5,2,3,7,2];
console.log('before call', a);
c(a);
console.log('after call',a);

Output:

"before call" [2, 3, 1, 5, 2, 3, 7, 2] "in func, before change" [2, 3, 1, 5, 2, 3, 7, 2] "in func, after change" [2, 17, 1, 5, 2, 3, 7, 2] "after call" [2, 3, 1, 5, 2, 3, 7, 2]

It's the fact that it is a 2D array is hosing you. Check out this stack overflow response on cloning 2D javascript arrays:

Multidimensional Array cloning using javascript

Now using this code:

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;
}

function c(a) {
  var l = a.clone();
  console.log('in func, before change',l);
  l[1].splice(1,1);
  console.log('in func, after change',l);
}

var a = [[2,3],[1,5,2],[3,7,2]];
console.log('before call', a);
c(a);
console.log('after call',a);

Output:

"before call" [[2, 3], [1, 5, 2], [3, 7, 2]] "in func, before change" [[2, 3], [1, 5, 2], [3, 7, 2]] "in func, after change" [[2, 3], [1, 2], [3, 7, 2]] "after call" [[2, 3], [1, 5, 2], [3, 7, 2]]

OTHER TIPS

.slice does not do a 'deep' copy. Since each element of 'a' is an array, iteslf, the elements of 'a' are references to those inner, otherwise–anonymous elements.

The array, 'l,' holds copies of the references, which copied references still point to the same 'objects' they refer to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top