JavaScript: copy array. Deep and Shallow clone copy explained.


This seems a simple problem to solve. We are working on our project and we need to duplicate an array.

This problem presents itself with more frequence if you are using a rective state manager that uses only immutables objects.

In general, we have to know if we need a shallow and deep copy of our array.

Shallow and deep copy

example of differences between shallow and deep copy in javascript
Shallow copy: only the original array object is cloned, the original content is referenced by the new array.

Deep copy: the objects inside the original array are cloned. Useful when you want to work on a copy of the original data.

The shallow copy allow us, i.e., to remove some references or add new references to the array. A possible use case is the temporary update of a list of elements before to persist the changes.
In this case, if the user doesn't want to save the changes, we can simply remove the second array. If we use this strategy every change in the object referenced by the array modify the original array too.

The deep copy creates independent objects from the original. In this case we can modify the elements of the array without any effect on the original array.

Shallow copy

A shallow copy simply creates a new array object with the same references to the objects of the original array.

javascript shallow copy

If you update an object inside the cloned array, the original object will be updated.

How to create a shallow copy

Here some examples, other methods are available (loop etc.):

// spread operator 
const newArraySpread = [... originalArray]; 
// slice 
const newArraySlice = originalArray.slice(); 
// Array class 
const newArrayFrom = Array.from(originalArray) 

According to some benchmarks, splice should be the fastest method. You can test with your data in this online benchmark:

Deep copy

A deep copy clones the original array and his content to new objects.

There are no references with the original array. You can modify the content without an impact on the original data.

javascript deep copy

How to create a deep copy using JavaScript or TypeScript

The 'easiest' method in JavaScript is to convert the array in JSON string and convert the JSON string in a new object.

const newArray = JSON.parse(JSON.stringify(originalArray)); 

This method is the easiest because it avoids a custom implementation, but it can have issues with circular references and big arrays (performance).

Deep Copy using lodash

Many developers prefer to use external and de facto standard libraries for some operations not included in the official language.

With lodash you can deep copy an array easily using cloneDeep:

import _ from "lodash"; 
var originalArray = ['JavaScript', 'TypeScript', 'Java']; 
var clonedArray = _.cloneDeep(originalArray); 

Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).