JavaScript copy, clone, or duplicate arrays and objects. Through this tutorial, i am going to show you how to copy, clone or duplicate an array and object in javaScript.
JavaScript Clone Array Method with Example
There are six methods to clone or copy an array and object in JavaScript; as shown below:
- Clone array using Spread Operator
- Slice Operator Clone array
- Concat Clone array
- Clone array using From() method
- Clone Array Using For loop
- Deep Copy Array
Clone array using Spread Operator
Using the spread operator, you can clone array in javaScript:
var arr = [1,2,3,4,5]; // Spread Operator var arr1 = [...arr];
Slice Operator using Clone array
Using the slice operator, you can clone array in javaScript:
var arr = [1,2,3,4,5]; // Slice Operator var arr2 = arr.slice();
Concat Clone array
Using the concat method, you can clone array in javaScript:
var arr = [1,2,3,4,5]; // Concat var arr3 = [].concat(arr)
Clone array using From() method
Using the from array method, you can clone array in javaScript:
var arr = [1,2,3,4,5]; // Array.from() var arr4 = Array.from(arr);
Clone Array Using For loop
Using the for loop, you can clone array in javaScript:
// For loop function arr5(arr) { let newArr = []; for(let i=0; i<arr.length; ++i) { newArr[i] = arr[i]; } return arr; }
Note: All of the above are shallow copies. If the original array is multi-dimensional there will be problems since you need a deep copy.
Deep Copy Array
You can solve this by serializing the entire array to JSON and then de-serializing it, but this results in bad performance and doesn’t work with special objects.
// Deep copy const dupArray = JSON.parse(JSON.stringify(arr))
Conclusion
In this clone, copy or duplicate arrays and objects tutorial, you have learned how to clone, copy or duplicate javascript arrays and objects using the simplest methods.