How to clone Arrays and Objects in JavaScript

Note: In JavaScript Array/object values are copied by reference not by value. So, beware while creating copy of arrays and objects.

1. Using spread operator (Shallow Copy):

// Clone Array
const data = [{name:"mike"}, {name:"natasha"}, {name:"alberto"}];
const dataCopy = [...data];
// Clone Object
const data = {name:"Alex",age:49,country:"United States"};
const dataCopy = {...data};

2. Using JSON.parse and JSON.stringify (Deep copy):

// Clone Array
const data = [{name:"mike"}, {name:"natasha"}, {name:"alberto"}];
const dataCopy = JSON.parse(JSON.stringify(data));
// Clone Object
const data = {name:"Alex",age:49,country:"United States"};
const dataCopy = JSON.parse(JSON.stringify(data));

3. Using Array.filter (Shallow copy)

// Clone Array
const data = [{name:"mike"}, {name:"natasha"}, {name:"alberto"}];
const dataCopy = data.filter(() => true);

4. Using Array.slice (Shallow copy)

// Clone Array
const data = [{name:"mike"}, {name:"natasha"}, {name:"alberto"}];
const dataCopy = data.slice();

4. Using Array.from (Shallow copy)

// Clone Array
const data = [{name:"mike"}, {name:"natasha"}, {name:"alberto"}];
const dataCopy = Array.from(data);