Copy / Duplicate an Array in JavaScript
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);
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.