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.

Javascript
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

Similar Reads

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....

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....

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....

Using the Object.assign() method

The Object.assign() method can also be used to create an cloned array of the existing array....

Using Array.from() method

The Array.from() method can also be use dot clone an array in TypeScript....

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....

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....