Open In App

How to Copy Array by Value in JavaScript ?

Last Updated : 28 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 = ["Geeksforgeeks","geek","GFG","geeks"];
const newArray = structuredClone(arr);
console.log(newArray);


Output:

['Geeksforgeeks', 'geek', 'GFG', 'geeks']


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads