Copying Arrays


Spread Syntax with Arrays

The spread syntax (...) is a powerful feature introduced in ES6 that allows an iterable such as an array to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. It provides a concise way to work with arrays for common tasks like copying, merging, and passing elements to functions.

Copying Arrays

The spread syntax provides a simple and effective way to create a shallow copy of an array. This is crucial for maintaining data immutability by avoiding direct modification of the original array.


Example 1: Basic Array Copy

// Original array of numbers
const originalNumbers = [1, 2, 3, 4, 5];

// Create a shallow copy using the spread syntax
const copiedNumbers = [...originalNumbers];

// Log both arrays to the console
console.log(originalNumbers); // Output: [1, 2, 3, 4, 5]
console.log(copiedNumbers);   // Output: [1, 2, 3, 4, 5]

Explanation

The code above demonstrates the most straightforward way to copy an array. The spread syntax ...originalNumbers expands the elements of originalNumbers inside the new array copiedNumbers, effectively creating a duplicate.


Example 2: Copying and Adding Elements

// Original array of strings
const originalFruits = ['Apple', 'Banana', 'Orange'];

// Create a copy and add new elements at the end
const extendedFruits = [...originalFruits, 'Mango', 'Grape'];

// Log the new array
console.log(extendedFruits); // Output: ['Apple', 'Banana', 'Orange', 'Mango', 'Grape']

Explanation

This example shows how to copy an existing array while simultaneously adding new elements. The spread syntax unpacks originalFruits, and then 'Mango' and 'Grape' are appended to the newly created extendedFruits array.


Example 3: Copying with Elements at the Beginning

// Original array of booleans
const originalBooleans = [true, false, true];

// Create a copy and add new elements at the beginning
const prependedBooleans = [false, ...originalBooleans];

// Log the new array
console.log(prependedBooleans); // Output: [false, true, false, true]

Explanation

Similar to the previous example, this demonstrates adding elements to a new array copy. Here, a new element false is placed at the beginning, followed by the expanded elements of the originalBooleans array.


Example 4: Copying a Portion of an Array

// Original array of mixed data types
const mixedData = [1, 'hello', true, null, { id: 1 }];

// Use slice() to get a portion and then spread it
const partialCopy = [...mixedData.slice(1, 4)];

// Log the new partial array
console.log(partialCopy); // Output: ['hello', true, null]

Explanation

This code snippet illustrates how to copy a specific segment of an array. The slice(1, 4) method first extracts elements from index 1 up to (but not including) index 4, and the spread syntax then expands these elements into a new array partialCopy.


Example 5: Shallow Copy with Nested Objects

// Original array with a nested object
const users = [{ name: 'Alice', city: 'New York' }, { name: 'Bob', city: 'London' }];

// Create a shallow copy
const copiedUsers = [...users];

// Modify a property of the nested object in the copied array
copiedUsers[0].city = 'San Francisco';

// Log both arrays to show the effect of shallow copy
console.log(users[0].city);       // Output: 'San Francisco'
console.log(copiedUsers[0].city); // Output: 'San Francisco'

Explanation

This example highlights the nature of a shallow copy. While the users array itself is copied, the nested objects within it are not. Both users and copiedUsers arrays contain references to the same user objects, so modifying an object in one array affects the other.


Example 6: Creating a Deep Copy (for comparison)

// Original array with nested objects
const products = [{ name: 'Laptop', specs: { ram: 16 } }];

// Creating a deep copy using JSON methods
const deepCopiedProducts = JSON.parse(JSON.stringify(products));

// Modify a nested property in the deep copy
deepCopiedProducts[0].specs.ram = 32;

// Log the nested property from both arrays
console.log(products[0].specs.ram);           // Output: 16
console.log(deepCopiedProducts[0].specs.ram); // Output: 32

Explanation

To create a true deep copy of an array with nested objects, the spread syntax alone is insufficient. This example uses JSON.stringify to convert the array to a JSON string and JSON.parse to parse it back into a new array, ensuring that even nested objects are duplicated.


Example 7: Copying an Array of Arrays

// Original nested array (matrix)
const matrix = [[1, 2], [3, 4]];

// Create a shallow copy of the outer array
const copiedMatrix = [...matrix];

// Modify an element in a nested array
copiedMatrix[0][0] = 99;

// Log both matrices to show the shallow copy effect
console.log(matrix[0][0]);       // Output: 99
console.log(copiedMatrix[0][0]); // Output: 99

Explanation

This code shows that when copying a multi-dimensional array, the spread syntax only performs a shallow copy of the outer array. The inner arrays are references, so a change in a nested array within copiedMatrix will also be reflected in the original matrix.