slice() method in TypeScript. This method is used to extract a certain section or parts of the elements of an array.
begin: This is the index position to start or begin the extraction. It is an integer value.
end: This is the index position to end the extraction. It has be an integer as well.
The value returned is the part of the array
array that was extracted.
// create arrays in TypeScript let names: string = ["Theodore", "James", "Peter", "Amaka"] let numbers : Array<number>; numbers = [12, 34, 5, 0.9] let cars : Array<string> = ["Porsche", "Toyota", "Lexus"] let randomValues : Array<string | number> = ["one",1, "two", 2, 56] // extract some parts of the arrays let extract1 = numbers.slice(2, 4) let extract2 = names.slice(1, 3) let extract3 = cars.slice(0, 2) let extract4 = randomValues.slice(4,5) // print out extracted values console.log(extract1) console.log(extract2) console.log(extract3) console.log(extract4)
In the above code, we see the following:
View all Courses