How to use Array.slice() method In Typescript
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.
const initialArr: any[] = [
{
emp_name: "Sushant Rana",
company: "w3wiki"
},
{
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: "w3wiki" },
{ emp_name: "Raghav Chadda", company: "Company 1" },
{ emp_name: "Christina Kaur", company: "Company 2" }]
How to Clone an Array in TypeScript ?
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:
Table of Content
- Using Array.slice() method
- Using Spread Operator
- Using JSON.stringify() and JSON.parse() methods together
- Using the Object.assign() method
- Using Array.from() method
- Using Array.concat() method
- Using a Custom Clone Function with Deep Copy