How to clone an array in JavaScript ?
Last Updated :
09 Nov, 2024
In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.
Here are some common use cases for cloning an array:
Using the Array.slice() Method
We use the slice method to create a shallow copy of an array. This method creates a new array with a subset of the elements from the original array.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = originalArray.slice();
console.log(clonedArray);
Using the spread Operator
Using the spread operator … is a concise and easy way to clone an array 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: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];
console.log(clonedArray);
Using the Array.from() Method
Using the Array.from() method is another way to clone an array 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: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = Array.from(originalArray);
console.log(clonedArray);
Using the Array.concat() Method
Using the Array.concat() method is another way to clone an array in JavaScript. This method creates a new array by concatenating two or more arrays together.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = [].concat(originalArray);
console.log(clonedArray);
Using a for loop
This method involves iterating through each element in the original array and copying each element into a new array.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = [];
for (let i = 0; i < originalArray.length; i++) {
clonedArray.push(originalArray[i]);
}
console.log(clonedArray);
Using the Array.map() Method
Using the Array.map() method is another way to clone an array in JavaScript. This method creates a new array by mapping each element from the original array to a new value.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = originalArray.map(x => x);
console.log(clonedArray);
Using the Array.from() method with a map function
Using the Array.from() method with a map function is another way to clone an array in JavaScript. This method creates a new array by mapping each element from the original array to a new value using a provided function.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = Array.from(originalArray, x => x);
console.log(clonedArray);
Using the Array.of() Method
This method creates a new array with the same elements as the original array.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = Array.of(...originalArray);
console.log(clonedArray);
Using the JSON.parse() and JSON.stringify() Methods
Using the JSON.parse() and JSON.stringify() methods is another way to clone an array in JavaScript. This method involves converting the original array to a JSON string and then parsing the JSON string to create a new array.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = JSON.parse(JSON.stringify(originalArray));
console.log(clonedArray);
Using the Object.assign() Method
Using the Object.assign() method is another way to clone an array in JavaScript. This method creates a new array by copying the properties of the original array to a new object.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const originalArray = [1, 2, 3];
const clonedArray = Object.assign([], originalArray);
console.log(clonedArray);
Using Array.reduce() Method
The Array.reduce() method executes a reducer function on each element of the array, resulting in a single output value. We can use it to construct a new array with the same elements as the original array.
Syntax:
array.reduce((accumulator, currentValue, currentIndex, array) => { ... }, initialValue);Example: In this example, we’ll use the Array.reduce() method to create a clone of an array.
JavaScript
// Input array
const originalArray = [1, 2, 3, 4];
// Cloning the array using reduce
const clonedArray = originalArray.reduce((acc, val) => {
acc.push(val);
return acc;
}, []);
// Display the original and cloned arrays
console.log("Original Array:", originalArray); // Output: [1, 2, 3, 4]
console.log("Cloned Array:", clonedArray); // Output: [1, 2, 3, 4]
OutputOriginal Array: [ 1, 2, 3, 4 ]
Cloned Array: [ 1, 2, 3, 4 ]
Note: Thus, When cloning an array, it is important to consider the complexity of the data and the performance requirements of the application.
Using the Array.flatMap() Method
Another approach to clone an array in JavaScript is by using the flatMap() method. The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. While its primary use case is for flattening arrays, it can also be utilized to clone an array by simply mapping each element to itself.
Example: In this example, we will use the flatMap() method to clone an array by mapping each element to itself.
JavaScript
const originalArray = [1, 2, 3, 4, 5];
const clonedArray = originalArray.flatMap(element => [element]);
console.log(clonedArray);
console.log(originalArray === clonedArray);
Output[ 1, 2, 3, 4, 5 ]
false
When to clone array?
If you want to perform some operations on an array, such as sorting, filtering, or mapping, but you don’t want to modify the original array, you can create a clone of the original array and perform the operations on the clone instead.
- When passing an array to a function as an argument, you may want to ensure that the function does not modify the original array. In this case, you can pass a clone of the array instead.
- If you want to preserve the original array for future reference, you can create a clone of the original array and use the clone for further processing or manipulation.
- If you have an array that contains objects or arrays as elements, and you want to avoid modifying the original objects or arrays, you can create a clone of the array to work with, so that changes to the objects or arrays in the clone do not affect the original objects or arrays.
Thus, cloning an array in JavaScript is a useful technique for working with arrays in a way that preserves the integrity of the original array and its elements.
Similar Reads
How to Add Elements to a JavaScript Array?
Here are different ways to add elements to an array in JavaScript. 1. Using push() MethodThe push() method adds one or more elements to the end of an array and returns the new length of the array. Syntax array.push( element1, element2, . . ., elementN );[GFGTABS] JavaScript const arr = [10, 20, 30,
3 min read
Create an Array of Given Size in JavaScript
The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values. Syntax cosnt arr = new Array( length )
4 min read
Insert at the Beginning of an Array in JavaScript
Following are different ways to add new elements at the beginning of an array 1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Remove Elements From a JavaScript Array
Here are the various methods to remove elements from a JavaScript Array 1. Using pop() methodThe pop() method removes and returns the last element of an array. This function decreases the length of the array by 1 every time the element is removed. [GFGTABS] javascript let a = ["Apple",
4 min read
Remove Duplicate Elements from JavaScript Array
To Remove the elements from an array we can use the JavaScript set method. Removing duplicate elements requires checking if the element is present more than one time in the array. 1. Using JavaScript Set() - Mostly UsedThe JavaScript Set() method creates an object containing only unique values. To r
3 min read
How to Remove Multiple Elements from Array in JavaScript?
Here are various methods to remove multiple elements from an array in JavaScript 1. Using filter() MethodThe filter() method creates a new array with the elements that pass the condition. This method does not change the original array. [GFGTABS] JavaScript let a = [1, 2, 3, 4, 5]; let remove = [2, 4
4 min read
Insert at the Beginning of an Array in JavaScript
Following are different ways to add new elements at the beginning of an array 1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Reverse an Array in JavaScript
Given an Array, the task is to reverse the array in JavaScript. Input: arr[] = {1, 2, 3} Output: {3, 2, 1} Input: arr[] = {"a", "c"} Output: {"c", "a"} Using reverse() (In-Place) - Best and Most Used[GFGTABS] JavaScript let a = [ 1, 2, 3, 4, 5 ]; a.reverse(); console.log(a); [/GFGTABS]Output[ 5, 4,
3 min read
JavaScript - Delete last Occurrence from JS Array
These are the following ways to remove the last Item from the given array: 1. Using pop() Method (Simple and Easiest Method for Any Array) The pop() method is used to get the last element of the given array it can also be used to remove the last element from the given array. [GFGTABS] JavaScript let
2 min read
Remove Empty Elements from an Array in JavaScript
Here are different approaches to remove empty elements from an Array in JavaScript. 1. Using array.filter() MethodThe array filter() method is used to create a new array from a given array consisting of elements that satisfy given conditions. array.filter( callback( element, index, arr ), thisValue
3 min read
Count Occurrences of All Items in an Array in JavaScript
Here are the different methods to count the occurrences of all items in an array in JavaScript 1. Using forEach() MethodThe arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.
4 min read
JavaScript- Add an Object to JS Array
These are the following ways to add an object to JS array: 1. Using JavaScript Array push() MethodThe push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this me
2 min read
JavaScript- Append in Array
These are the following ways to append an element to the JS array: 1. Using Array.push() MethodJavaScript array.push() Method is used to add one or more elements to the end of the array. [GFGTABS] JavaScript let a = [ 10, 20, 30, 40, 50 ]; a.push(90); console.log(a); [/GFGTABS]Output[ 10, 20, 30, 40
2 min read
JavaScript - Select a Random Element from JS Array
Selecting a random element from array in JavaScript is done by accessing an element using random index from the array. We can select the random element using the Math.random() function. 1. Using Math.random() MethodThe Math.random() method is used to get the random number between 0 to 1 (1 exclusive
2 min read
How to Remove Duplicates from an Array of Objects in JavaScript?
Here are some effective methods to remove duplicates from an array of objects in JavaScript 1. Using filter() and findIndex() Methods - Most UsedThe simplest way to remove duplicates is by using filter() and findIndex(). This method keeps the first occurrence of each object with a unique property (l
3 min read
Split an Array into Chunks in JavaScript
Here are different methods to split an array into chunks in JavaScript. 1. Using slice() MethodThe array slice() method returns a new array containing the selected elements. This method selects the elements starting from the given start argument and ends at, but excluding the given end argument. Syn
4 min read
JavaScript - Sum of an JS Array
These are the following ways to get the sum of the elements of the given array: 1. Using for loop (Simple for all Array)We are simply going to iterate over all the elements of the array using a JavaScript for loop to find the sum. [GFGTABS] JavaScript let a = [4, 8, 7, 13, 12] let sum = 0; for (let
2 min read
Find the min/max element of an Array using JavaScript
To find the minimum or maximum element in a JavaScript array, use Math.min or Math.max with the spread operator. JavaScript offers several methods to achieve this, each with its advantages. Using Math.min() and Math.max() Methods The Math object's Math.min() and Math.max() methods are static methods
2 min read
JavaScript - Get first and last Item of JS Array
These are the following ways to get first and last element of the given array: 1. Using length PropertyThe array length property in JavaScript is used to set or return the number of elements in an array. [GFGTABS] JavaScript let arr = [3, 2, 3, 4, 5]; let f = arr[0]; let l = arr[arr.length - 1]; con
2 min read
Insert at the End of an Array in JavaScript
Here are different ways to add an item at the end of array 1. Using push() Method - Most Used : The JavaScript Array push() Method is used to add one or more values to the end of the array. This method changes the length of the array by the number of elements added to the array. [GFGTABS] JavaScript
3 min read
How to add elements to an existing array dynamically in JavaScript ?
An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type. In this article, we will see how to add new elements to an existing array dynamically in Javascript. We will discuss two methods in this article i.e. push() method and dynamically adding an elemen
4 min read
How to move an array element from one array position to another in JavaScript?
In JavaScript, we can access an array element as in other programming languages like C, C++, Java, etc. Also, there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another
5 min read
JavaScript - Inserting Multiple Items at Specific Index in JS Array
We can insert an item into Array at a specific index using the JavaScript Array splice method. This method removes the elements from the mentioned index and add items at that specific position. 1. Using array.splice() MethodJavaScript array.splice() Method is an inbuilt method in JavaScript that is
3 min read
Copy Array Items Into Another Array in JavaScript
Here are the various methods to copy array items into another array in JavaScript 1. Using the Spread Operator (...)The spread operator (...) is a concise syntax introduced in ES6 that allows us to expand iterable objects, like arrays, into individual elements. [GFGTABS] JavaScript const a1 = [1, 2,
3 min read
JavaScript - Remove n Elements From End Array
Here are the different methods to remove n elements from the end of a given array in JavaScript 1. Using splice() Methodsplice() method is used to modify an array by adding or removing elements from it. It accepts the index from which the modification has to be made and the number of elements to del
3 min read
How to clone an array in JavaScript ?
In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array. Here are some common use cases for cloning an array: Table of Content Using the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsin
6 min read
How to find the index of all occurrence of elements in an array using JavaScript ?
The index of all occurrences of elements refers to the positions of each instance of a specific element within an array. We find these indices to locate all occurrences of an element for various operations like counting, filtering, or manipulation within the array. To find the index of all occurrenc
4 min read
Check if an array is empty or not in JavaScript
These are the following ways to check whether the given array is empty or not: 1. The length Property - mostly usedThe length property can be used to get the length of the given array if it returns 0 then the length of the array is 0 means the given array is empty else the array have the elements. [
1 min read