0

In this plunk I have an example of an array of objects a that I copy with slice() to b. I alter one of the objects in a but it changes also b. Isn't slice supposed to copy the array, including its contents? I need a and b to have different pointers.

Javascript

var a = [{x1:1, x2:2}, {x1:3, x2:4}];

var b = a.slice();


a[1].x1 = 5;


console.log(b[1]);

this prints:

x1: 5 
x2: 4
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • [`.slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) makes a shadow copy, not a deep copy. – Spencer Wieczorek Jan 22 '17 at 03:19
  • how can I achieve a copy? do I have to do that manually? – ps0604 Jan 22 '17 at 03:19
  • @Raphael the questions are different, in my question I'm asking about slice, in the question you pointed slice is the answer – ps0604 Jan 22 '17 at 03:21

2 Answers2

1

From MDN:

For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array does not affect the other array.

Performing a deep copy on objects in the array is difficult, but this answer suggests a way to do it, as long as your array only contains JSON-serializable content:

var clonedArray = JSON.parse(JSON.stringify(originalArray));

Community
  • 1
  • 1
tklg
  • 2,572
  • 2
  • 19
  • 24
  • [This question](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript?rq=1) has a variety of answers on how to do a "deep clone". jQuery, Lodash, Underscore, and other libraries have fairly slick methods available. – random_user_name Jan 22 '17 at 03:27
1

You can try to do Deep copy with jQuery:

var b = $.extend(true,{},a);

This does a proper deep copy of all your variables.

poushy
  • 1,114
  • 11
  • 17