how to clone arrays in javascript

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.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.