Wednesday, September 25, 2024
Google search engine
HomeLanguagesJavascriptHow to Copy Array by Value in JavaScript ?

How to Copy Array by Value in JavaScript ?

In this article, we will see how to create a copy of an array by value using JavaScript. Javascript has various ways to clone the array.

We can use some methods to create a copy of an array that is given below:

Method 1: Using Spread Operator

Using the spread operator … is a concise and easy way to copy an array by value in JavaScript. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.

Example:

Javascript




const originalArr = [1, 2, 3, 4, 5, 6];
const clonedArr = [...originalArr];
  
console.log(clonedArr);


Output

[ 1, 2, 3, 4, 5, 6 ]

Method 2: Using Array.from() Method

Using the Array.from() method is another way to copy an array by its value in JavaScript. This method creates a new array from an existing array, using an optional mapping function to transform the values in the new array.

Example:

Javascript




const originalArr = [1, 2, 3, 5, 6, 4];
const clonedArr = Array.from(originalArr);
  
console.log(clonedArr);


Output

[ 1, 2, 3, 5, 6, 4 ]

Method 3: Using Array.slice() Method

We use the slice() method to create a copy of an array by its value in JavaScript. This method creates a new array with a subset of the elements from the original array.

Example:

Javascript




const originalArr = [1, 2, 3, 4, 5, 6];
const clonedArr = originalArr.slice();
  
console.log(clonedArr);


Output

[ 1, 2, 3, 4, 5, 6 ]

Method 4: Using structuredClone() Method

We can also use the modern structuredClone() method for deep cloning of an array. This can be done using the structured clone algorithm.

Example:

Javascript




const arr = ["Geeksforneveropen","geek","GFG","neveropen"];
const newArray = structuredClone(arr);
console.log(newArray);


Output:

['Geeksforneveropen', 'geek', 'GFG', 'neveropen']

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments