Open In App

TypeScript Array lastIndexOf() Method

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Array.prototype.lastIndexOf() method in TypeScript is used to find the last index at which a given element can be found in the array, searching backwards from the fromIndex. It returns the index of the found element, or -1 if the element is not present.

Syntax:

array.lastIndexOf(searchElement[, fromIndex])

Parameter: This method accepts two parameter as mentioned above and described below: 

  • searchElement : This parameter is the element to locate in the array.
  • fromIndex : This parameter is the index at which to start searching backwards.

Return Value: This method returns the index of the found element from the last. 

Below examples illustrate the Array lastIndexOf() method in TypeScript.

Examples of Array lastIndexOf() Method

Example 1: Basic Usage of lastIndexOf()

In this example, we will demonstrate the basic usage of the lastIndexOf() method to find the last occurrence of an element in an array.

const arr: number[] = [1, 2, 3, 2, 1];
const index: number = arr.lastIndexOf(2);

console.log(index);

Output: 

3

Example 2: 

const arr: number[] = [1, 2, 3, 2, 1];
const index1: number = arr.lastIndexOf(2, 4);
console.log(index1);
const index2: number = arr.lastIndexOf(2, 2);
console.log(index2);
const index3: number = arr.lastIndexOf(3, 4);
console.log(index3);

Output: 

3
1 2

Next Article

Similar Reads