7

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);
Dave
  • 2,764
  • 2
  • 15
  • 27

2 Answers2

8

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

If it's a flat array with no circular references, you can use

var copied_array = JSON.parse(JSON.stringify(original_array));

This works for flat objects as well.

Divyanth Jayaraj
  • 950
  • 4
  • 12
  • 29