JavaScript Array lastIndexOf() method


The lastIndexOf() method in JavaScript is used to determine the index of the last occurrence of a specified element in an array. If the element is not found, it returns -1. This method is case-sensitive and can be useful for searching through arrays from the end towards the beginning.

Syntax:


let index = array.lastIndexOf(searchElement, fromIndex);
  • searchElement: The element to search for in the array.
  • fromIndex (optional): The index at which to begin the search backwards. The default is the array's length minus one. If the specified index is greater than or equal to the array's length, the search starts from the end of the array.

Return Value:

  • The index of the last occurrence of the specified element within the array, or -1 if the element is not found.

Key Points:

  • Case-sensitive: The search is case-sensitive for string elements.
  • Returns the last index: If the element appears multiple times in the array, lastIndexOf() will return the index of the last occurrence.
  • Starts searching from a specified index: You can start searching from a specific index using the fromIndex parameter.

Example 1: Basic usage (Finding a number)

let numbers = [10, 20, 30, 20, 50]; let index = numbers.lastIndexOf(20); // Find the last index of 20 console.log(index); // 3

Example 2: Searching with a starting index

let numbers = [10, 20, 30, 20, 50]; let index = numbers.lastIndexOf(20, 2); // Start searching from index 2 console.log(index); // 1 (the last occurrence before index 2)

Example 3: Element not found

let fruits = ['apple', 'banana', 'orange']; let index = fruits.lastIndexOf('grape'); // Look for an element that does not exist console.log(index); // -1

Example 4: Searching for a string with case sensitivity

let words = ['hello', 'world', 'Hello']; let index1 = words.lastIndexOf('hello'); // Check for lowercase 'hello' let index2 = words.lastIndexOf('Hello'); // Check for uppercase 'Hello' console.log(index1); // -1 (not found) console.log(index2); // 2

Example 5: Using fromIndex to search backwards


let numbers = [1, 2, 3, 4, 5, 3]; let index = numbers.lastIndexOf(3, 4); // Start searching from index 4 console.log(index); // 2 (the last occurrence of 3 before index 4)

Example 6: Searching with negative fromIndex

let numbers = [10, 20, 30, 40, 50]; let index = numbers.lastIndexOf(30, -2); // Start searching from the 2nd last index console.log(index); // 2 (last occurrence of 30 found before index -2)

Summary:

  • The lastIndexOf() method is useful for searching for an element in an array and retrieving the index of its last occurrence.
  • It returns the index of the last occurrence of the specified element or -1 if the element is not present, making it a valuable tool for reverse searching within arrays.
  • The optional fromIndex parameter allows for customized searching, including specifying a starting point from which to search backwards.