Copy array items into another array

Learn copy array items into another array with practical examples, diagrams, and best practices. Covers javascript, arrays development techniques with visual explanations.

Efficiently Copy Array Items into Another Array in JavaScript

Hero image for Copy array items into another array

Learn various JavaScript techniques to copy elements from one array to another, understanding their nuances and best use cases for shallow and deep copies.

Copying array items is a fundamental operation in JavaScript development. Whether you need to duplicate an array, merge arrays, or extract a subset of elements, understanding the different methods available is crucial. This article explores several common and efficient ways to copy array items, highlighting the distinction between shallow and deep copies, which is vital for preventing unintended side effects.

Understanding Shallow vs. Deep Copies

Before diving into specific methods, it's important to grasp the difference between shallow and deep copies. This distinction primarily matters when dealing with arrays containing objects or other arrays (nested structures).

  • Shallow Copy: Creates a new array, but the elements themselves are not duplicated. If the original array contains objects, the new array will contain references to the same objects. Modifying an object in the copied array will also affect the original array.
  • Deep Copy: Creates a new array and recursively duplicates all nested objects and arrays. This ensures that the copied array is completely independent of the original, meaning changes to one will not affect the other.
flowchart TD
    A[Original Array] --> B{Contains Primitives?}
    B -- Yes --> C[Shallow Copy is Sufficient]
    B -- No (Contains Objects/Arrays) --> D{Need Independent Copy?}
    D -- Yes --> E[Perform Deep Copy]
    D -- No --> F[Perform Shallow Copy]

Decision flow for choosing between shallow and deep array copies.

Common Methods for Shallow Copying Arrays

For most scenarios involving primitive values (numbers, strings, booleans) or when you intentionally want shared references for objects, shallow copy methods are efficient and straightforward.

// 1. Using the Spread Operator (...)
const originalArray = [1, 2, 3];
const copiedArraySpread = [...originalArray];
console.log(copiedArraySpread); // Output: [1, 2, 3]

// 2. Using Array.prototype.slice()
const originalArray2 = ['a', 'b', 'c'];
const copiedArraySlice = originalArray2.slice();
console.log(copiedArraySlice); // Output: ['a', 'b', 'c']

// 3. Using Array.from()
const originalArray3 = [true, false];
const copiedArrayFrom = Array.from(originalArray3);
console.log(copiedArrayFrom); // Output: [true, false]

// 4. Using Array.prototype.concat()
const originalArray4 = [10, 20];
const copiedArrayConcat = originalArray4.concat();
console.log(copiedArrayConcat); // Output: [10, 20]

Examples of shallow copying arrays using common JavaScript methods.

Performing a Deep Copy of Arrays

When your array contains nested objects or arrays, a shallow copy won't suffice if you need complete independence. Deep copying ensures that all nested structures are also duplicated.

// Using JSON.parse(JSON.stringify())
const originalArrayNested = [
  { id: 1, name: 'Alice' },
  [4, 5, 6]
];

const deepCopiedArrayJSON = JSON.parse(JSON.stringify(originalArrayNested));

// Modify the deep copy
deepCopiedArrayJSON[0].name = 'Bob';
deepCopiedArrayJSON[1][0] = 99;

console.log(originalArrayNested[0].name); // Output: 'Alice' (original unaffected)
console.log(deepCopiedArrayJSON[0].name); // Output: 'Bob'
console.log(originalArrayNested[1][0]); // Output: 4 (original unaffected)
console.log(deepCopiedArrayJSON[1][0]); // Output: 99

Deep copying an array with nested objects and arrays using JSON serialization.

For more robust deep cloning, especially in complex applications, libraries like Lodash provide highly optimized and feature-rich cloneDeep functions that handle edge cases like circular references and various data types gracefully.