JavaScript - How to duplicate an array

Shallow and deep copy

shallow and deep copy 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.

Shallow copy

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

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.

deep copy

How to create a deep copy

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

WebApp built by Marco using SpringBoot, Java 17, Mustache, Markdown and in Azure