Arrays are used widely to store data, and sometimes, we are required to clone an array. Let’s now learn all the methods to do it.
How Can Array Be Cloned In Javascript?
Cloning an array means we are making another copy of the given array.
When we pass an array or any data, it is best practice to keep the original data intact and not modify it; thus, we need to clone the array so that we can perform all our needed operations and manipulation on the cloned array and our original array remains intact.
Cloning the array allows for safe manipulation without impacting the original elements and maintaining data integrity.
In Javascript, there are different methods to clone an array. Some of the commonly used methods are:
- Using slice() operation
- Using concat() operation
- Using the spread operator
- Using Array.from() operation
- Using map() operation
- Using JSON.parse() and JSON.stringify() methods
Let’s explore all the methods with the implementation:
1) Cloning Array Using Slice() Operation
We can use the slice method to copy a portion of the array. The slice method takes some arguments based on which it creates a new array by selecting that portion of the array.
When the slice method is used without passing any arguments then it clones the whole array without selecting some portion of the array. The cloned array is a shallow copy of the original array, which means that if the original array contains objects or nested arrays, they will be referenced in the cloned array.
Here is an example to demonstrate this:
const originalArray = [1, 2, 3, 4, 5]; //slice() without arguments const clonedArray = originalArray.slice(); console.log("cloned array is: "); console.log(clonedArray);
Console
cloned array is:
[1, 2, 3, 4, 5]
Our clonedArray will contain the same values as the originalArray as we have used the slice method without passing any arguments.
However, if we pass the index as arguments, i.e., the start index and end index, we can clone a part of the array in JavaScript. Elements before the end index will be cloned. For example:
const originalArray = [1, 2, 3, 4, 5]; //start index is 0 and the end index is 3 const clonedArray = originalArray.slice(0,3); console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
cloned array is:
[1, 2, 3]
Like this, we cloned the first three elements of the array by passing (0,3) as arguments,i.e., Elements from 0 index to (3-1) index.
2) Cloning Array using concat() Operation
In JavaScript, the concat operation is used to join/concatenate two arrays. When we use the concat operation without any arguments in javascript, it creates a new array which is a copy of the original array and thus we can create a clone of the array easily using the concat operation. This method also creates a shallow copy of the original array.
Here is an example to demonstrate this:
const originalArray = [1, 2, 3, 4, 5]; //using concat() operation const clonedArray = originalArray.concat(); console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
cloned array is:
[1, 2, 3, 4, 5]
Our clonedArray will contain the same values as the originalArray as we have used the concat() method without passing any arguments.
As shallow copying is done, if the array contains objects inside it, references to them are copied. Therefore, if we modify these objects in the cloned array then these changes will also reflect in the original array.
Here is an example:
const originalArray = [1, 2, [3, 4], [5]]; // Shallow copy using concat() const clonedArray = originalArray.concat(); // Modify the clonedArray clonedArray[2][0] = 'modified'; console.log("Original array is: "); console.log(originalArray); console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
Original array:
[1, 2, [ 'modified', 4 ], [5]]
Cloned array:
[1, 2, [ 'modified', 4 ], [5]]
We can see element ‘3’ is modified in both arrays.
3) Cloning Array using the Spread Operator
The spread operator is widely used in JavaScript and can be used to create a copy of the array. As its name suggests, what it does is it spreads or copies values present in the original array into a new array. This method also creates a shallow copy.
Here is an example to demonstrate this:
const originalArray = [1, 2, 3, 4, 5]; //using the spread operator const clonedArray = [...originalArray]; console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
cloned array is:
[1, 2, 3, 4, 5]
4) Cloning Array using Array.from() Operation
The Array.from() method in Javascript creates a new instance of the iterable object that is passed into it. As the array is an iterable object, we can clone that array by passing it as an argument in the method.
A shallow copy is created using this method.
Here is an example to demonstrate this:
const originalArray = [1, 2, 3, 4, 5]; //using Array.from() operation const clonedArray = Array.from(originalArray); console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
cloned array is:
[1, 2, 3, 4, 5]
5) Cloning Array using map() Operation
In JavaScript, the map method is used to create a new array by changing the elements of the original array based on the function that we pass into it.
The map function takes a callback and modifies all elements of the original array based on that callback function. Thus, we can create a clone of the array by passing a callback function that simply returns the original value passed into it. The map method also creates a shallow copy.
Here is an example to demonstrate this:
const originalArray = [1, 2, 3, 4, 5]; //using map() operation const clonedArray = originalArray.map(item => item); console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
cloned array is:
[1, 2, 3, 4, 5]
Our callback function inside the map method takes all values of the original array as an item, and it simply returns that item without modifying it.
6) Using JSON.parse() and JSON.stringify()
As we have covered shallow copy methods above, this method is different as it deep copies the elements. Here, the nested objects are also copied, and references are not passed. JSON.stringify()
serializes the object, and JSON.parse()
deserializes the object.
For example:
// Original array with nested array const originalArray = [1, 2, [3, 4]]; // Deep copy using JSON.parse() and JSON.stringify() const clonedArray = JSON.parse(JSON.stringify(originalArray)); // Modify the nested array in the deep copy clonedArray[2][0] = 'modified'; console.log("Original array is: "); console.log(originalArray); console.log("cloned array is: "); console.log(clonedArray);
OUTPUT:
The original array is:
[1, 2, [3, 4]]
clonedArray is:
[1, 2, [ 'modified', 4 ]]
This creates a completely independent deep copy, and we can observe that modifying the nested array in the deep copy doesn’t affect the original array.
One important thing is that this method works well for simple data structures but may not be suitable for objects with functions or non-JSON-safe data. For more complex scenarios, external libraries like Lodash provide deep cloning functions.
Conclusion
So, we have thoroughly explored cloning an array in JavaScript. By cloning arrays, developers can avoid unexpected side effects and write more predictable and maintainable code.