DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

Cloning Arrays in JavaScript

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

There are a few ways to clone an array in JavaScript,

Object.assign

Object.assign allows us to make a shallow copy of any kind of object including arrays.

For example:

const a = [1,2,3];
const b = Object.assign([], a); // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Array.slice

The Array.slice function returns a copy of the original array.

For example:

const a = [1,2,3];
const b = a.slice(0); // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Array.from

The Array.slice function returns a copy of the original array. It takes array like objects like Set and it also takes an array as an argument.

const a = [1,2,3];
const b = Array.from(a); // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Spread Operator

The fastest way to copy an array, which is available with ES6 or later, is the spread operator.

const a = [1,2,3];
const b = [...a]; // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

JSON.parse and JSON.stringify

This allows for deep copy of an array and only works if the objects in the array are plain objects. It can be used like this:

const a = [1,2,3];
const b = JSON.parse(JSON.stringify(a)); // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
revolist profile image
Maks

Would be gr8 to have benchmark for such topics.