1

Simple issue I am facing.

  arr = [[1,2,3],[3,4,5],[6,7,8]];
  x = arr[0];
  x[0] = 2; //x returns [2,2,3]

At the same time arr is also updated to [[2,2,3],[3,4,5],[6,7,8]] How can I prevent this.I don't want arr to change and why does this happen?

vramazing
  • 94
  • 1
  • 1
  • 6
  • If you dont want `arr` value to change than why are you assigning value `x[0]=2` since `x=arr[0]` is not copying but creating array by reference?? – wrangler Oct 28 '17 at 16:40
  • 2
    Use `x = arr[0].slice()`. You’re mutating the array by reference, because you don’t create a copy by assigning the array to a variable. – Sebastian Simon Oct 28 '17 at 16:40
  • 1
    Possible duplicate of [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array) – Sebastian Simon Oct 28 '17 at 16:41
  • 1
    Possible duplicate of [Copying array by value in JavaScript](https://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) – JJJ Oct 28 '17 at 16:53

1 Answers1

0

The = operator does not make a copy of the data.

The = operator creates a new reference to the same data.

An easy fix would be to do the following when assigning the value of x:

x = arr[0].slice();

Zomtorg
  • 153
  • 1
  • 11