Copy/Clone an Array or Object in JavaScript The Right Way [Examples]

How to Copy/Clone JavaScript Array

This tutorial will show you how to properly copy/clone an array or object in JavaScript – it’s not as simple as it seems!

Copying an array or object may seem simple – but JavaScript throws a spanner in the works – the fact that when you assign the value of one variable to another it references the original variable. This means that if the value of the original variable is changed, the value of the copy will change too!

To get around this, you will need to clone the array – ensuring new variables with their own values are created in a new array. JavaScript does not contain a built in way to do this, but there are of course various ways it can be achieved.

How Not to Do it!

Your first instinct may be to do the following:

var pets = ['fish', 'parrot', 'cat'];
var petsClone = pets;

THIS WILL NOT WORK!

petsClone will simply become a reference to the variable pets – not a copy. pets and petsClone won’t be copies of each other, they will both be names pointing to the same variable.

If one is updated, the other will change, which may not be the behaviour you want if you are copying an array.

Shallow vs Deep Copy – Safely Cloning ALL Values in an Array in JavaScript

When cloning arrays in JavaScript you’ll see references to shallow and deep cloning or copying.

Shallow cloning will only clone the values in the first level of the array. Any nested values will NOT be cloned, so watch out for this one if you’re working with multidimensional arrays! Shallow cloning is still useful for when you are working with two dimensional arrays and want to focus on performance and code simplicity.

Shallow Cloning Arrays Using ES6 Spread Syntax (…)

This is probably the simplest way to shallow copy/clone an array, using JavaScripts spread syntax:

var pets = ['fish', 'parrot', 'cat'];
var petsClone = [...pets];

The spread syntax expands the values within an array, so calling it inside a newly declared array will clone the contents of the other array into the new array.

Using JSON Functions to Deep Clone an Array

Below, a multidimensional or nested array is declared. The array pets contains two sub-arrays, each containing their own values. Attempt to use the spread syntax above will not clone the values in these sub arrays, they will be referenced.

You could write a complex loop to dive into each sub-array and clone the values, but there is a much better, if a little hacky solution – converting the original array to JSON, and then decoding it into a new array.

var pets = [['dog', 'cat'], ['fish', 'frog']];
var petsCopy = JSON.parse(JSON.stringify(pets));

Hacky solutions are often the best solutions. JSON.stringify() is used to convert the original array to a JSON string, and JSON.parse() is used to decode that string back into a JavaScript array, an entirely separate clone of the original, which is then assigned to a new variable.

Watch Out for Custom Classes/Objects

If you are deep cloning an array containing custom object classes, they will be converted to generic objects, and any references within them will be lost!

Whether or not this is a problem is entirely dependent on what you’re trying to accomplish. You may need to loop through the cloned array and use Object.assign() to ensure cloned objects are of the right class.

Test, Test, Test

If you’re building something mission critical, or which deals with money (like an online shop), and you are duplicating arrays, make sure you test your code and make sure your code is behaving in the way you intend it to!

JavaScript’s behaviour of referencing variables instead of duplicating them is a common hurdle for new JavaScript developers. Getting into the habit of testing your code will make sure you spot any issues before they become a problem for your users.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *