0

I'm searching for a solution to copy an array from another one so I can manipulate my second array. But the problem is when I make a change in the second, it also affects the first.

Example :

var array1 = [1 , 2 , 3];
var array2 = array1;

array2.splice(0,2);

Result :

array2 : [3];
array1 : [3];

But what I expect :

array1 : [1 , 2 , 3];
array2 : [3];

Any solution for this ?

1 Answers1

-1

Try the below code

var array1 = [1 , 2 , 3];
var array2 = array1.slice();

array2.splice(0,2);
Sagar V
  • 12,158
  • 7
  • 41
  • 68
bubjavier
  • 982
  • 8
  • 11
  • 1
    It's typically more desirable to use `.slice()` instead of `.splice()` when "copying" to avoid modifying the original array in the process. – Jonathan Lonowski Jul 18 '17 at 18:35