How do I clone a JavaScript array?

You can clone a JavaScript array by calling Object.assign(), array.reduce() or array.forEach(). The Object.assign() method allows you to shallow copy the values of all enumerable properties and methods from one or more source objects to the target object (passing an array as the source object and an empty object as the target). The array.reduce() method sequentially processes each element in an array, saving the intermediate result. The reduce() method takes as an argument a callback function that is executed for each element in the array. The array.forEach() method allows you to execute the given function once for each element in the array. The passed function can perform any operation on the elements of the given array. The Spread Operator ("...") is available since ECMAScript 6 and can be used to expand an array where object literals should be used. In this JavaScript array cloning example, we use the spread operator ("..."). Click on Execute to run JavaScript Clone Array Example online and view the results.
Loading...