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.

TypeScript
// Driver code
let arr: number[] = [11, 89, 23, 7, 98];

// use of splice() method 
let removed: number[] = arr.splice(2, 0, 11);

// printing
console.log(removed);
console.log("Modified array :"+arr);

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.

TypeScript
// Driver code
let arr: string[] = ["G", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"];
let val: string[];

// use of splice() method
val = arr.splice(0, 5);
console.log(val);
console.log(arr);

Output: 

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

Explore