Dave Dave - 3 months ago 16
Javascript Question

How to create copy of array?

I have array:

var array = ["a", "b", "c"];


I need save this array to another variable

var save = array;


Now I need splice from
save
first index but when I try it, the index is removed from both arrays.



var array = ["a", "b", "c"];
var save = array;

save.splice(0, 1);
console.log(array);
console.log(save);




Answer

You need to copy the array using Array#slice otherwise save holds the reference to the original array(Both variables are pointing to the same array).

var save = array.slice();

var array = ["a", "b", "c"];
var save = array.slice();

save.splice(0, 1);
console.log(array);
console.log(save);