VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-array-splice-method/

⇱ TypeScript Array splice() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript Array splice() Method

Last Updated : 12 Jul, 2024

The Array.splice() is an inbuilt TypeScript function that changes the content of an array by adding new elements while removing old ones. It takes an index, a count of elements to remove, and optional elements to add, returning the removed elements and modifying the original array.

Syntax

array.splice(index, howMany, [element1][, ..., elementN]); 

Parameter: This method accepts three parameters as mentioned above and described below: 

  • index : This parameter is the index at which to start changing the array.
  • howMany : This parameter is the integer indicating the number of old array elements to remove.
  • element1, ..., elementN : This parameter is the elements to add to the array.

Return Value: This method returns the extracted array. 

Below example illustrate the  Array splice() method in TypeScriptJS:

Example 1: Inserting Elements

In this example The splice() method inserts 11 at index 2 in the array without removing any elements. removed is an empty array since no elements are deleted. The modified array is printed.

Output:

[]

Example 2: Adding and Removing Elements

In this example we are using splice() to remove the first 5 elements from the array arr, storing them in val, and then prints both val and the modified arr.

Output:

[ 'G', 'e', 'e', 'k', 's' ]
[
'f', 'o', 'r',
'g', 'e', 'e',
'k', 's'
]
Comment
Article Tags:
Article Tags:

Explore