There are multiple ways to create a clone of an array in JavaScript. Some of the most common ways are:
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.
let originalArray = [1, 2, 3]; let clonedArray = [...originalArray]; console.log(clonedArray); // [1, 2, 3]
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.
let originalArray = [1, 2, 3]; let clonedArray = originalArray.slice(); console.log(clonedArray); // [1, 2, 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.
let originalArray = [1, 2, 3]; let clonedArray = [].concat(originalArray); console.log(clonedArray); // [1, 2, 3]
Using theArray.from() method: The Array.from() method creates a new array with the elements of the original array.
let originalArray = [1, 2, 3]; let clonedArray = Array.from(originalArray); console.log(clonedArray); // [1, 2, 3]
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.
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.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions