Multiple ways to clone an array in JavaScript


There are multiple ways to create a clone of an array in JavaScript. Some of the most common ways are:

Method-1

Using theSpread operator: The spread operator allows you to spread the elements of an array into a new array. It creates a shallow copy of the array.

Example
let originalArray = [1, 2, 3];
let clonedArray = [...originalArray];
console.log(clonedArray);  // [1, 2, 3]

Method-2

Using theslice() method: The slice() method creates a shallow copy of the array. It takes no arguments, it will create a copy of the entire array.

Example
let originalArray = [1, 2, 3];
let clonedArray = originalArray.slice();
console.log(clonedArray);  // [1, 2, 3]

Method-3

Using theconcat() method: The concat() method creates a new array with the elements of the original array and any additional elements that you pass to it.

Example
let originalArray = [1, 2, 3];
let clonedArray = [].concat(originalArray);
console.log(clonedArray);  // [1, 2, 3]

Method-4

Using theArray.from() method: The Array.from() method creates a new array with the elements of the original array.

Example
let originalArray = [1, 2, 3];
let clonedArray = Array.from(originalArray);
console.log(clonedArray);  // [1, 2, 3]

Method-5

Using theJSON.parse() and JSON.stringify(): JSON.stringify() method convert the javascript object into json format and JSON.parse() method converts json string into javascript object.

Example
let originalArray = [1, 2, 3];
let clonedArray = JSON.parse(JSON.stringify(originalArray));
console.log(clonedArray);  // [1, 2, 3]

It's important to note that all the above methods create a shallow copy of the array, which means it will copy the elements of the original array but not the objects inside the array.

List of Programs


JS Practical Questions & Answers


JS Practical Project