Copy / Duplicate an Array in JavaScript

Last modified on January 6, 2020 22 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

In this guide, we are going to learn how to clone an array in JavaScript. We will learn two ways to copay an array. Let’s see the ways:

Spread Operator

The spread operator (…) helps us to duplicate an array. It is available in ES6 only. Here’s the example:

// let an array
const array1 = ['data1','data2','data3'];

// duplicate the array
const array2 = [...array1];

console.log(array2);

Slice Method

We can also use slice() to duplicate an array. Let’s see the example:

// let an array
const array1 = ['data1','data2','data3'];

// duplicate the array
const array2 = array1.slice();

console.log(array2);

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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