2

How can I copy the array without changing the original array value?

var arr1 = [];
var arr2 = [];

arr1 = [{price: 10},{price: 20}];

console.log(arr1);

arr2[0] = arr1[0];
arr2[0].price += 5;

console.log(arr2);

//output arr1 = [{price: 15},{price: 20}]; Why???
//output arr2 = [{price: 15}];
Vico
  • 23
  • 1
  • 5

4 Answers4

4

deep copy the array using JSON.parse(JSON.stringify(arr1))

var arr1 = [];

arr1 = [{
  price: 10
}, {
  price: 20
}];
var arr2 = JSON.parse(JSON.stringify(arr1))
arr2[0].price += 5;
console.log(arr2, arr1);
brk
  • 48,835
  • 10
  • 56
  • 78
0

My friend, you are dealing with object pointers, essentially what your doing is giving arr1[0] an alias called arr2[0]. and when you change 1 you change both. One way to fix this is to declare:

arr2=arr1
arr2.length=1;
arr2[0].price+=5;

By not referencing the object directly, but just duplicating the array, we arnt allowing the object to make pointers in memory, and the arr2.length is to get rid of the second element.

JakeTheSnake
  • 372
  • 1
  • 11
0

You are changing the value of arr1[0] by doing below:

arr2[0].price+= 5; // eventually arr2[0] = arr1[0] and that's why it is getting updated due to object pointers
Umesh
  • 2,704
  • 19
  • 21
0

You are not creating a new variable with the content of arr1. You are only copying the arr1 pointer to a new variable called arr2. Thus, as the object pointed by arr1 and arr2 is the same, if you modify one you modify the other.

The solution would be to create a copy of the array, for example: arr2 = arr1.copy()

YanSym
  • 51
  • 5