Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create copy of array? [duplicate]

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);
like image 533
Dave Avatar asked Sep 06 '16 18:09

Dave


People also ask

Which method of an array creates a duplicate copy?

arraycopy() method. arraycopy can be used to copy a subset of an array.

How do I make a copy of an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

How do you make a shallow copy of an array?

Array Clone – Shallow Copy In Java, to create clone of array, you should use clone() method of array. It creates a shallow copy of array. Cloning always creates shallow copy of array. Any change (in original array) will be reflected in cloned array as well.

What is clone in array?

The copyOfRange() method is used to copy the elements of the specified range of the original array into clone array. The syntax of the copyOfRange() method is as follows: public static int[] copyOfRange(int[] original, int from, int to)


1 Answers

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);
like image 185
Pranav C Balan Avatar answered Oct 24 '22 15:10

Pranav C Balan