TypeScript is a superset of JavaScript. Wherever JavaScript runs, TypeScript runs, too. We can use the slice()
method in TypeScript. This method is used to extract a certain section or parts of the elements of an array.
array.slice(begin, end)
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 TypeScriptlet 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 arrayslet 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 valuesconsole.log(extract1)console.log(extract2)console.log(extract3)console.log(extract4)
In the above code, we see the following:
slice()
method.