Skip to content

How to clone an array in JavaScript?

In this tutorial, we are going to learn about different ways to copy or clone an array in JavaScript. To duplicate an array, most often used method is slice() but you can also use ES6’s spread operator to clone an array.

Advertisements

Array.slice()

slice() method returns a shallow copy of an array based on the provided start/end index you provide.

const j = ['Jim', 'sucks', 'dick'];

const jcopy = j.slice();

//jcopy has ['Jim', 'sucks', 'dick']

If you want to copy a part of an array, you can pass the start index and end index to slice() method.

const j = ['Jim', 'sucks', 'dick'];

const jcopy = j.slice(0,1);

//jcopy has ['Jim', 'sucks']

ES6 Spread operator

The spread operator … has been very convenient to clone an array since ES6 was introduced.

const j = ['Jim', 'sucks', 'dick'];

// ES6 way
const jcopyES6 = [...j];
console.log(jcopyES6);

//['Jim', 'sucks', 'dick']
Advertisements

Array.concat

concat() method copies one array into another and returns the merged array.

const j = ['Jim', 'sucks', 'dick'];

const jcopy = [].concat(j);

console.log(jcopy);
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

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.