How to Clone an Array in TypeScript ?
Last Updated :
04 Jun, 2024
A cloned array is an array that contains all the items or elements contained by an already existing array in the same order. A cloned array does not affect the original array. If there is any change made in the cloned array it will not change that item in the original array.
We can use the following methods to clone an array in TypeScript:
Using Array.slice() method
The Array.slice() method can be used to create a copy or clone of the already existing array in another array.
Syntax:
const clonedArrayName = originalArray.slice();
Example: The below code example implements the slice() method to make the clone an array.
JavaScript
const initialArr: any[] = [
{
emp_name: "Sushant Rana",
company: "GeeksforGeeks"
},
{
emp_name: "Raghav Chadda",
company: "Company 1"
},
{
emp_name: "Christina Kaur",
company: "Company 2"
}
];
const clonedArr: any[] = initialArr.slice();
console.log(clonedArr);
Output:
[{ emp_name: "Sushant Rana", company: "GeeksforGeeks" },
{ emp_name: "Raghav Chadda", company: "Company 1" },
{ emp_name: "Christina Kaur", company: "Company 2" }]
Using Spread Operator
The spread operator can also be used to create the clone of an array using the three dots syntax (...) before the name of the original array inside the square brackets.
Syntax:
const clonedArrayName = [...originalArray];
Example: The below code example will explain the use of the spread operator to create a clone of the array.
JavaScript
const initialArr: any[] = [
{
emp_name: "Sushant Rana",
company: "GeeksforGeeks"
},
{
emp_name: "Raghav Chadda",
company: "Company 1"
},
{
emp_name: "Christina Kaur",
company: "Company 2"
}
];
const clonedArr: any[] = [...initialArr];
console.log(clonedArr);
Output:
[{ emp_name: "Sushant Rana", company: "GeeksforGeeks" },
{ emp_name: "Raghav Chadda", company: "Company 1" },
{ emp_name: "Christina Kaur", company: "Company 2" }]
Using JSON.stringify() and JSON.parse() methods together
The JSON.stringify() method will change the array into a JSON string and then the JSON.parse() method will be used to parse and create a cloned array from that JSON string.
Syntax:
const clonedArrayName = JSON.parse(JSON.stringify(existingArray)) as typeof existingArray;
Example: The below code example uses the above approach to create a clone of the existing array.
JavaScript
const initialArr: any[] = [
{
emp_name: "Sushant Rana",
company: "GeeksforGeeks"
},
{
emp_name: "Raghav Chadda",
company: "Company 1"
},
{
emp_name: "Christina Kaur",
company: "Company 2"
}
];
const clonedArr: any[] =
JSON.parse(JSON.stringify(initialArr)) as typeof initialArr;
console.log(clonedArr);
Output:
[{ emp_name: "Sushant Rana", company: "GeeksforGeeks" },
{ emp_name: "Raghav Chadda", company: "Company 1" },
{ emp_name: "Christina Kaur", company: "Company 2" }]
Using the Object.assign() method
The Object.assign() method can also be used to create an cloned array of the existing array.
Syntax:
const clonedArrayName = Object.assign([], originalArray);
Example: The below code example practically implements the Object.assign() method to clone an array in TypeScript.
JavaScript
const initialArr: any[] = [
{
emp_name: "Sushant Rana",
company: "GeeksforGeeks"
},
{
emp_name: "Raghav Chadda",
company: "Company 1"
},
{
emp_name: "Christina Kaur",
company: "Company 2"
}
];
const clonedArr: any[] = Object.assign([], initialArr);
console.log(clonedArr);
Output:
[{ emp_name: "Sushant Rana", company: "GeeksforGeeks" },
{ emp_name: "Raghav Chadda", company: "Company 1" },
{ emp_name: "Christina Kaur", company: "Company 2" }]
Using Array.from() method
The Array.from() method can also be use dot clone an array in TypeScript.
Syntax:
const clonedArrayName = originalArray.from();
Example: The below code example illustrates the use of the Array.from() method to clone an array in TypeScript.
JavaScript
const initialArr: any[] = [
{
emp_name: "Sushant Rana",
company: "GeeksforGeeks"
},
{
emp_name: "Raghav Chadda",
company: "Company 1"
},
{
emp_name: "Christina Kaur",
company: "Company 2"
}
];
const clonedArr: any[] = Array.from(initialArr);
console.log(clonedArr);
Output:
[{ emp_name: "Sushant Rana", company: "GeeksforGeeks" },
{ emp_name: "Raghav Chadda", company: "Company 1" },
{ emp_name: "Christina Kaur", company: "Company 2" }]
Using Array.concat() method
In this approach we will use concat() method which is used to merge two or more arrays. When used with an empty array, it effectively clones the original array.
Syntax:
const clonedArray = [].concat(originalArray);
Example: The below code example illustrates the use of the Array.concat() method to clone an array in TypeScript.
JavaScript
const originalArray: any[] = [
{ emp_name: "Saurabh Puri", company: "Nisarga" },
{ emp_name: "Prasad bade", company: "Pwd" },
{ emp_name: "Manya khedkar", company: "MK construction" }
];
const clonedArray = [].concat(originalArray);
console.log(clonedArray);
Output:
[
{ emp_name: 'Saurabh Puri', company: 'Nisarga' },
{ emp_name: 'Prasad bade', company: 'Pwd' },
{ emp_name: 'Manya khedkar', company: 'MK construction' }
]
Using a Custom Clone Function with Deep Copy
To ensure a deep copy of arrays containing objects or nested structures in TypeScript, you can create a custom function that recursively clones each element. This approach is useful for scenarios where you need to guarantee that modifications to nested elements in the cloned array do not affect the original.
JavaScript
function deepClone<T>(items: T[]): T[] {
return items.map(item => {
if (Array.isArray(item)) {
return deepClone(item); // Handle nested arrays
} else if (typeof item === 'object' && item !== null) {
// Correctly cloning each object property
const clonedObject: any = {};
for (const key in item) {
clonedObject[key] = deepClone([item[key]])[0];
}
return clonedObject;
}
return item; // Return primitive types unchanged
});
}
// Example usage:
const originalArray = [
{ emp_name: 'Saurabh Puri', company: 'Nisarga' },
{ emp_name: 'Prasad bade', company: 'Pwd' },
{ emp_name: 'Manya khedkar', company: 'MK construction' }
];
const clonedArray = deepClone(originalArray);
console.log(clonedArray);
Output:
[
{ emp_name: 'Saurabh Puri', company: 'Nisarga' },
{ emp_name: 'Prasad bade', company: 'Pwd' },
{ emp_name: 'Manya khedkar', company: 'MK construction' }
]
Similar Reads
How to Declare an Empty Array in TypeScript?
TypeScript provides a robust type system that allows you to define and manage data structures more effectively than in plain JavaScript. One common task is declaring empty arrays with specific types, ensuring that your array holds only values of the intended type. These are the following ways to dec
2 min read
How to Convert a Set to an Array in TypeScript ?
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
5 min read
How to Sort an Array in TypeScript ?
Array sorting is the process of arranging the elements within an array in a specified order, often either ascending or descending based on predetermined criteria. Below are the approaches used to sort an array in typescript: Table of Content Method 1: Using sort methodMethod 2: Spread OperatorMethod
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 Declare an Array of Strings in TypeScript ?
Arrays are fundamental data structures in TypeScript, enabling developers to manage collections of elements efficiently. Below are the approaches to declare an Array of strings in TypeScript: Table of Content Square Brackets NotationArray ConstructorSquare Brackets NotationUsing square brackets nota
1 min read
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.
6 min read
How to Flatten Array of Arrays in TypeScript ?
Array flattening is the process of converting a nested array (an array of arrays) into a single-dimensional array where all the elements are at the same level. In other words, it involves transforming an array that contains other arrays as elements into an array that only contains non-array elements
4 min read
How to Convert a Dictionary to an Array in TypeScript ?
In TypeScript, converting a dictionary(an object) into an Array can be useful in scenarios where you need to work with the values in a more iterable and flexible manner. These are the following approaches: Table of Content Using Object.keys methodUsing Object.values methodUsing Object.entries method
3 min read
How to Declare a Fixed Length Array in TypeScript ?
To declare a Fixed-length Array in TypeScript you can use a Tuple. Tuple types allow you to specify the types for each element in the array and, importantly, define a fixed number of elements in a specific order. In this article, we are going to learn how to declare a fixed-length array in TypeScrip
3 min read
How to use Associative Array in TypeScript ?
Typescript Associative arrays are objects in which indexes are replaced by user-defined keys. Associative Array can be used like a regular array, but the only difference is that it can be accessed using strings instead of numbers. Syntax:let associativeArray: { [key: string]: string } = { key1: "val
2 min read