TypeScript Array slice() Method
Last Updated :
08 Aug, 2024
Improve
The Array.slice() method in TypeScript is a built-in function used to extract a section of an array and return it as a new array. This method does not alter the original array.
Syntax:
array.slice( begin [,end] );
Parameter: This method accepts two parameters as mentioned above and described below:
- begin : This parameter is the Zero-based index at which to begin extraction.
- end : This parameter is the Zero-based index at which to end extraction.
Return Value: This method returns the extracted arra.
The below example illustrates the Array slice() method in TypeScriptJS:
Example 1: In this example we defines a numeric array arr, then uses the slice() method to extract a portion of it into val.
// Driver code
let arr: number[] = [11, 89, 23, 7, 98];
// use of slice() method
let val: number[] = arr.slice(2, 4);
// printing
console.log(val);
Output:
[ 23, 7 ]
Example 2: In this example we defines a string array arr, then uses the slice() method to extract portions of the array into val.
// Driver code
let arr: string[] = ["G", "e", "e", "k", "s", "f", "o", "r",
"g", "e", "e", "k", "s"];
let val: string[];
// Use of slice() method
val = arr.slice(2, 6);
console.log(val);
val = arr.slice(5, 8);
console.log(val);
Output:
[ 'e', 'k', 's', 'f' ]
[ 'f', 'o', 'r' ]