How to copy an array in JavaScript (deep copy, shallow copy)?

This article introduces methods for copying an array in JavaScript, which include shallow copy and deep copy techniques. It covers using array methods such as `slice()`, `concat()`, spread syntax, `Array.from()`, and recursive functions.

Home > Blog > How to copy an array in JavaScript (deep copy, shallow copy)?

In JavaScript, arrays are one of the data structures we often use. Sometimes, we need to copy arrays to operate without modifying the original array. Today, we will delve into array copying in JavaScript, including two different copying methods: shallow copy and deep copy.

Array shallow copy

First, let's talk about shallow copy. Shallow copy only performs one layer and cannot perform deep copying. It is a reference to a copied array, not its contents. This means that when you modify the copied array, the original array will also be affected. So, how to perform shallow copy? Here are several methods:

1. Using the array's slice () method

// Example of array
let originalArray = [1, 2, 3];
let shallowCopyArray = originalArray.slice();

console.log(shallowCopyArray);  // Output: [1, 2, 3]

2. Using the array's concat () method

let originalArray = [1, 2, 3];
let shallowCopyArray = originalArray.concat();

console.log(shallowCopyArray); // Output: [1, 2, 3]

3. Use array expansion syntax

let originalArray = [1, 2, 3];
let shallowCopyArray = [...originalArray];

console.log(shallowCopyArray); // Output: [1, 2, 3]

4. Use the Array.from () method

let originalArray = [1, 2, 3];
let shallowCopyArray = Array.from(originalArray);

console.log(shallowCopyArray); // Output: [1, 2, 3]

The above example shows how to use different shallow copy methods to copy arrays. The resulting copy usually affects the original object or array during modification, so please be aware. In addition, for nested objects or arrays, shallow copy may cause some problems, such as the inability to copy deep nested content, so deep copy is needed.

Array deep copy

Deep copy copies the array and all its nested objects and the contents of the array, rather than just copying references, which ensures that the copied array is completely independent of the original array. There are several ways to implement deep copy, including recursion function, using JSON.parse () and JSON.stringify () , as well as some methods provided by third-party libraries, which are introduced below:

1. Use the recursion function

A recursion function is a method that iterates through each property and sub-property of an object and copies each property. When an object's property is a primitive type, its value is directly copied; when the property is an object, recursion calls itself to copy the sub-object. In this way, it is ensured that a completely independent copy of the original object is created, even if the object contains nested objects.

function deepCopy(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return obj; // Return directly if it's a primitive type or null
    }

    let copy = Array.isArray(obj) ? [] : {}; // Create a new object or array

    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            copy[key] = deepCopy(obj[key]); // Recursively copy each property of the object
        }
    }

    return copy;
}

// Example usage
let originalObject = { a: 1, b: { c: 2 } };
let deepCopyObject = deepCopy(originalObject);

console.log(deepCopyObject); // Output: { a: 1, b: { c: 2 } }

The output result is as follows:

copy an array in JavaScript

2. Use JSON.stringify () and JSON.parse ()

The JSON.stringify () method converts JavaScript values to JSON strings, and the JSON.parse () method converts JSON strings to JavaScript values. By converting objects to JSON strings and then parsing the JSON strings into new objects, deep replication can be achieved. The advantage of this method is that it is simple and easy to use, but for some special objects, such as objects containing functions or circular references, there may be some limitations, so recursion is still a safe choice.

// Deep copy object
let originalObject = { a: 1, b: { c: 2 } };
let deepCopyObject = JSON.parse(JSON.stringify(originalObject));

console.log(deepCopyObject); // Output: { a: 1, b: { c: 2 } }

The output result is as follows:

copy an array in JavaScript

Notes

When copying arrays, there are several common pitfalls to be aware of, such as the impact of circular references and prototype chains. Therefore, we need to write robust code and test the copy results to ensure their correctness and performance. In addition, for large datasets, we also need to pay attention to the performance issues that copy operations may bring.

Summary

In summary, array copying is an important and common operation in JavaScript. Through this article, we have gained a deep understanding of the concepts and implementation methods of shallow and deep copying. In practical applications, please choose the appropriate copying method according to the specific situation and handle the copying operation carefully to ensure the correctness and performance of the program.

Reference link:

How to copy an array in JavaScript (deep copy, shallow copy)?
This article introduces methods for copying an array in JavaScript, which include shallow copy and deep copy techniques. It covers using array methods such as `slice()`, `concat()`, spread syntax, `Array.from()`, and recursive functions.

Learn more: