Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
typescript
last index
communitycreator

How to get the last index of an array element in TypeScript

Theodore Kelechukwu Onyejiaku

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 TypeScript
let 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 elements
console.log(names.lastIndexOf("Theodore"))  // 0 
console.log(numbers.lastIndexOf(12))        // 3
console.log(cars.lastIndexOf("Toyota"))     // 3
Get last index of an element using the lastIndexOf() method

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.

RELATED TAGS

array
typescript
last index
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring