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:

Table of Content

  • Using Spread Operator
  • Using Array.from() Method
  • Method 3: Using Array.slice() Method
  • Using structuredClone() Method
  • Using the map()

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 ]

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 ]

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

Output:

['w3wiki', 'geek', 'GFG', 'Beginner']

Using the map()

Using map() to copy an array in JavaScript involves creating a new array by applying a function to each element of the original array. This method is useful for creating a shallow copy or transforming elements during the copying process:

Example:

JavaScript
let originalArray = [1, 2, 3, 4];
let copiedArray = originalArray.map(element => element);

console.log(copiedArray); // Output: [1, 2, 3, 4]

// To prove it's a different array:
copiedArray.push(5);
console.log(originalArray);
console.log(copiedArray); // Output: [1, 2, 3, 4, 5]

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