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

2
  • 1
    Try array.slice(). Commented Sep 6, 2016 at 18:11
  • 1
    Read up on value type vs reference type for the reason why this happens. Commented Sep 6, 2016 at 18:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Dave : glad to help
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.