lastIndexOf() Method in JavaScript

JavaScript2 min read
lastIndexOf() Method in JavaScript
javascriptlastindexof methodarray methods

The lastIndexOf() method in JavaScript is used to find the index of the last occurrence of a specified value in an array.

lastIndexOf() Method in JavaScript

  • The lastIndexOf() method in JavaScript is used to find the index of the last occurrence of a specified value in an array.
  • It returns the index of the last matching element.
  • The search starts from the last index of the array but only shows the last occurrence.
  • It takes two arguments:
    • search-element: The value to search for.
    • from-index (optional): The index from which to start the search. If not provided, it searches from the end of the array.
  • If the element is not found, it returns -1.

Example:

  • Let's take an array names with some duplicate names.
const names = ['john', 'max', 'alex', 'tony', 'smith', 'tony', 'jack'];
  • To find the last occurrence of tony in the array, use the lastIndexOf() method:
const indexNo = names.lastIndexOf('tony'); console.log(indexNo); // Output: 5

The search starts from the end of the array and returns 5 because the last occurrence of tony is at index 5.

  • Now, if you provide a from-index value, the search starts from that index and searches backward.
const indexNo = names.lastIndexOf('tony', 4); console.log(indexNo); // Output: // 3

With from-index set to 4, the search starts from index 4 and finds the last occurrence of tony at index 3.

  • The lastIndexOf() method helps in finding the last occurrence of a value, optionally from a specified starting point.