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
3
  • .slice() makes a shadow copy, not a deep copy. Commented Jan 22, 2017 at 3:19
  • how can I achieve a copy? do I have to do that manually? Commented Jan 22, 2017 at 3:19
  • @Raphael the questions are different, in my question I'm asking about slice, in the question you pointed slice is the answer Commented Jan 22, 2017 at 3:21

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

1 Comment

This question has a variety of answers on how to do a "deep clone". jQuery, Lodash, Underscore, and other libraries have fairly slick methods available.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.