-1

Array 1

var arr1 = ["abc", "pqr", "xyz"];

Now I moved this array to another array.

var arr2 = arr1;
arr2.push("lmn");

Now when I alert arr1, It is showing "abc", "pqr", "xyz", "lmn" but I pushed "lmn" in arr2?

I don't want to change arr1 values.

Prashant Patil
  • 2,463
  • 1
  • 15
  • 33

2 Answers2

1

If you use the spread operator, it will fix the problem. It will look something like thisvar arr2 = [...arr1]

0

You have reference to the same array. You can either use spread operator or slice for cloning the value of array.

var arr1 = ["abc", "pqr", "xyz"];

var arr2 = [...arr1]; // or  arr1.slice(0)

arr2.push('imn');

console.log(arr1);
console.log(arr2);
gorak
  • 5,233
  • 1
  • 7
  • 19