Catalin Vasile

I'm a design-focused engineer.

JavaScript Bits: How to copy an Array?

In JavaScript there are multiple ways to copy an Array type. In this short guide, you will learn how to copy them using both ES5 and ES6 methods. You will also learn how to make both shallow or deep clones of an Array.

Here’s a quick table of contents for your reference:

The simplest and fastest way to clone an array is by using the .slice() method. Keep in mind that using .slice() would make a shallow copy of the Array, where all object references are copied by reference.

const fruits = ['Apples', 'Watermelons', 'Strawberries'];

const clonedFruits = fruits.slice();

console.log(clonedFruits); // Apples, Watermelons, Strawberries

2. Shallow Copy Using Concat (ES5)

Another method of copying an Array is by using the .concat() method. Keep in mind that .concat() also returns just a shallow copy of the Array and all object references are copied by reference.

const fruits = ['Apples', 'Watermelons', 'Strawberries'];

const clonedFruits = [].concat(fruits);

console.log(clonedFruits); // Apples, Watermelons, Strawberries

3. Shallow Copy Using Destructuring (ES6)

If you are using ES6, you can also destructure your Array type using the spread operator in order to clone it. This method also makes a shallow copy.

const fruits = ['Apples', 'Watermelons', 'Strawberries'];

const clonedFruits = [...fruits];

console.log(clonedFruits); // Apples, Watermelons, Strawberries

4. Deep Copy Using JSON (ES5)

A quick workaround to making deep copies would be by stringifying and then parsing an Array. It’s worth keeping in mind that this will work only with JSON compatible data types. Therefore, all functions will not be copied and all custom object types will inherit from Object after the copy.

const fruits = [
    ['Apples'],
    ['Watermelons'],
    ['Strawberries']
];

const clonedFruits = JSON.parse(JSON.stringify(fruits));

console.log(clonedFruits); // [['Apples'], ['Watermelons'], ['Strawberries']]

5. Deep Copy Using Lodash (ES5)

The simplest way would be by using Lodash’s cloneDeep() method.

import _cloneDeep from "lodash.clonedeep";

const fruits = [
    { 'Apples': 5 },
    { 'Watermelons': 10 },
    { 'Strawberries': 4}
];

const deepClonedFruits = _cloneDeep(fruits);

Conclusion

I hope this short guide has helped you get a better understanding of the methods available for copying Array types in JavaScript.

Let me know in the comments below if there’s another method you think I’ve missed.

Subscribe

Be the first to know when I publish a new article on the blog.

No spam. You can unsubscribe at any time.


Comments