9

JavaScript - How to duplicate an array

 3 years ago
source link: https://marco.dev/javascript-duplicate-array
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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: https://jsben.ch/lO6C5

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

Author

Marco Molteni

Marco Molteni Blog


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK