How to get the last index of an array element in TypeScript
Overview
TypeScript allows us to do more with JavaScript. It gives us additional syntax, better error handling and lots more. We can get the last index of an element in an array in TypeScript using the lastIndexOf() method. This method returns the index of the last occurrence of an element in an array.
Syntax
array.lastIndexOf(element)
Syntax for lastIndexOf() method in TypeScript
Parameters
element: The element we want to find the last occurrence of in the array.
Return value
An integer value representing the index of the last occurrence of the given element in the array.
Example
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let numbers : Array<number>;numbers = [12, 34, 5, 12, 0.9]let cars : Array<string> = ["Porsche", "Toyota", "Lexus", "Toyota"]// get last index of some elementsconsole.log(names.lastIndexOf("Theodore")) // 0console.log(numbers.lastIndexOf(12)) // 3console.log(cars.lastIndexOf("Toyota")) // 3
Explanation
- Lines 2–5: We create some arrays.
- Lines 8–10: We get the last index of some elements and print their indices to the console.