Search code examples
javascriptarraysduplicationsplice

duplicating arrays javascript splicing


I have come across a strange bug in my code and I cannot understand why it happens.

I have an array array1. I duplicate array1 by making array2 equal to array1. I then modify array2 using splice to add a number. Array1 should not be touched? But both output the same change.

var array1 = [0,1,2,3,4,5];
var array2 = array1;
array2.splice(1,0,1) //add  
console.log(array1);
console.log(array2);

I am assuming I am confusing array assignment? What is the proper way to duplicate arrays without this happening?

Cheers


Solution

  • Use array1.concat() to duplicate the array instead of passing a reference to array1:

    var array1 = [0,1,2,3,4,5];
    var array2 = array1.concat();
    array2.splice(1,0,1) //add  
    console.log(array1);
    console.log(array2);
    

    array.concat() can concatenate multiple arrays, but if you pass an empty argument, you're effectively concatenating an array with nothing: cloning the array.

    Note that any array and object elements are still references:

    var a = [ [1], 2];
    var b = a.concat();
    b[0][0] = 0;
    console.log(b); // gives 0,2
    console.log(c); // gives 0,2 too!