How to Clone Arrays in JavaScript

In this short tip post, we will learn how to clone the existing array in JavaScript.

Objective

Create a copy of the array using JavaScript function.

Approach

Generally, people do the iteration over the existing array and copy each element to new array to create a clone.

We can use slice() function to create the clone of an array.

Code

Here is the code.

var arr =  [ 10, 20, 30, 4, 5, 6, 112, 333, 4, 2, 5, 66 ]

var arr2 = arr.slice(0);

console.log('Actual array ', arr);
console.log('Cloned array', arr2);

Check out the codepen for the live demo.

See the Pen
clone array
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.

Pankaj Kumar
Pankaj Kumar
Articles: 206