Copying array by value in JavaScript

6 October 2016By Rich @Black Sand Solutions
  • Javascript

I learnt something new today - after tearing my hair out for longer than I care to admit.

Copying array by value in JavaScript

I was trying to clone an array in Javascript - that is, break the reference between the original array and it's clone.

I thought this would do it

var clonedArray =  Array.from(originalArray);

or this:

var clonedArray =  this.originalArray.slice();

And it did, sort of; adding items to the new array did not update the clone.

BUT, updating an object in the original array, updated the equivalent object in the cloned array.

Yikes, what?!

It turns out that:

for references, strings and numbers (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.
MDN

So, as well as cloning the array, we need to clone each object in the array too.

We can do this a few ways:

var clonedArray = originalArray.map(function (obj) {
                      return Object.assign({}, obj);
                  });

Or, if the objects in the array have no methods:

var newArray = JSON.parse(JSON.stringify(orgArray));

I'll add more ways of doing this as I found them, and also performance notes.

All Posts