Copy / Duplicate an Array in JavaScript

Published on Jan 04, 2020

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);

Comments (0)