How to clone an array in JavaScript ?
In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.
Here are some common use cases for cloning an array:
Table of Content
- Using the Array.slice() Method
- Using the spread Operator
- Using the Array.from() Method
- Using the Array.concat() Method
- Using a for loop
- Using the Array.map() Method
- Using the Array.from() method with a map function
- Using the Array.of() Method
- Using the JSON.parse() and JSON.stringify() Methods
- Using the Object.assign() Method
- Using Array.reduce() Method
- Using the Array.flatMap() Method
- When to clone array?
Using the Array.slice() Method
We use the slice method to create a shallow copy of an array. This method creates a new array with a subset of the elements from the original array.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = originalArray.slice();
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the spread Operator
Using the spread operator ... is a concise and easy way to clone an array in JavaScript. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the Array.from() Method
Using the Array.from() method is another way to clone an array in JavaScript. This method creates a new array from an existing array, using an optional mapping function to transform the values in the new array.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = Array.from(originalArray);
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the Array.concat() Method
Using the Array.concat() method is another way to clone an array in JavaScript. This method creates a new array by concatenating two or more arrays together.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = [].concat(originalArray);
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using a for loop
This method involves iterating through each element in the original array and copying each element into a new array.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = [];
for (let i = 0; i < originalArray.length; i++) {
clonedArray.push(originalArray[i]);
}
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the Array.map() Method
Using the Array.map() method is another way to clone an array in JavaScript. This method creates a new array by mapping each element from the original array to a new value.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = originalArray.map(x => x);
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the Array.from() method with a map function
Using the Array.from() method with a map function is another way to clone an array in JavaScript. This method creates a new array by mapping each element from the original array to a new value using a provided function.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = Array.from(originalArray, x => x);
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the Array.of() Method
This method creates a new array with the same elements as the original array.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = Array.of(...originalArray);
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the JSON.parse() and JSON.stringify() Methods
Using the JSON.parse() and JSON.stringify() methods is another way to clone an array in JavaScript. This method involves converting the original array to a JSON string and then parsing the JSON string to create a new array.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = JSON.parse(JSON.stringify(originalArray));
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using the Object.assign() Method
Using the Object.assign() method is another way to clone an array in JavaScript. This method creates a new array by copying the properties of the original array to a new object.
Example: This example shows the implementation of the above-explained approach.
const originalArray = [1, 2, 3];
const clonedArray = Object.assign([], originalArray);
console.log(clonedArray);
Output
[ 1, 2, 3 ]
Using Array.reduce() Method
The Array.reduce() method executes a reducer function on each element of the array, resulting in a single output value. We can use it to construct a new array with the same elements as the original array.
Syntax:
array.reduce((accumulator, currentValue, currentIndex, array) => { ... }, initialValue);
Example: In this example, we'll use the Array.reduce() method to create a clone of an array.
// Input array
const originalArray = [1, 2, 3, 4];
// Cloning the array using reduce
const clonedArray = originalArray.reduce((acc, val) => {
acc.push(val);
return acc;
}, []);
// Display the original and cloned arrays
console.log("Original Array:", originalArray); // Output: [1, 2, 3, 4]
console.log("Cloned Array:", clonedArray); // Output: [1, 2, 3, 4]
Output
Original Array: [ 1, 2, 3, 4 ] Cloned Array: [ 1, 2, 3, 4 ]
Note: Thus, When cloning an array, it is important to consider the complexity of the data and the performance requirements of the application.
Using the Array.flatMap() Method
Another approach to clone an array in JavaScript is by using the flatMap() method. The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. While its primary use case is for flattening arrays, it can also be utilized to clone an array by simply mapping each element to itself.
Example: In this example, we will use the flatMap() method to clone an array by mapping each element to itself.
const originalArray = [1, 2, 3, 4, 5];
const clonedArray = originalArray.flatMap(element => [element]);
console.log(clonedArray);
console.log(originalArray === clonedArray);
Output
[ 1, 2, 3, 4, 5 ] false
When to clone array?
If you want to perform some operations on an array, such as sorting, filtering, or mapping, but you don't want to modify the original array, you can create a clone of the original array and perform the operations on the clone instead.
- When passing an array to a function as an argument, you may want to ensure that the function does not modify the original array. In this case, you can pass a clone of the array instead.
- If you want to preserve the original array for future reference, you can create a clone of the original array and use the clone for further processing or manipulation.
- If you have an array that contains objects or arrays as elements, and you want to avoid modifying the original objects or arrays, you can create a clone of the array to work with, so that changes to the objects or arrays in the clone do not affect the original objects or arrays.
Thus, cloning an array in JavaScript is a useful technique for working with arrays in a way that preserves the integrity of the original array and its elements.