jsguides

Array.prototype.lastIndexOf()

lastIndexOf(searchElement, fromIndex)

The lastIndexOf() method returns the last index at which a given element can be found in an array. If the element is not found, it returns -1.

How it differs from indexOf()

const colors = ['red', 'blue', 'green', 'blue', 'yellow'];

colors.indexOf('blue');     // 1 (first occurrence)
colors.lastIndexOf('blue'); // 3 (last occurrence)

Like indexOf(), lastIndexOf() relies on strict equality (===) to determine whether two values match. This means the search is type-sensitive — a number 1 and a string '1' are treated as distinct, and no implicit coercion is applied during the comparison.

Strict equality comparison

lastIndexOf() uses strict equality (===) to compare elements. This means type coercion does not occur:

const mixed = [1, '1', true, 'true'];

mixed.lastIndexOf(1);    // 0 (number)
mixed.lastIndexOf('1'); // 1 (string)
mixed.lastIndexOf(true); // 2 (boolean)

The fromIndex parameter

The optional second parameter fromIndex specifies the starting position for the backward search. By default, it searches from the end of the array.

Important behavior:

  • When fromIndex is omitted, search starts from arr.length - 1
  • A positive fromIndex counts forward from the start
  • A negative fromIndex counts backward from the end
const letters = ['a', 'b', 'c', 'b', 'a', 'b'];

// Search from the end (default)
letters.lastIndexOf('b'); // 5

// Start searching backwards from index 3
letters.lastIndexOf('b', 3); // 3

// Negative fromIndex: start from 2 positions before the end
letters.lastIndexOf('b', -2); // 3

The examples below show lastIndexOf() in practical scenarios: locating characters in a string split into an array, restricting the search window to exclude elements near the end, and identifying values that appear more than once. Each scenario builds on the behaviors covered so far.

Examples

Finding the last occurrence

const sentence = 'the quick brown fox jumps over the lazy dog';
const chars = sentence.split('');

// Find last 'o'
const lastO = chars.lastIndexOf('o');
console.log(lastO); // 43
console.log(chars[lastO]); // 'o'

The fromIndex parameter is especially useful when you want to ignore elements near the end of the array. By passing a lower starting position, you restrict the backward scan to only the elements up to that index — effectively searching within a prefix of the array without creating a slice.

Limiting search range with fromIndex

const items = ['apple', 'banana', 'cherry', 'banana', 'date'];

// Find 'banana' before index 3 (exclusive)
const index = items.lastIndexOf('banana', 2);
console.log(index); // 1

lastIndexOf() can also help detect whether an element appears more than once: if arr.indexOf(x) !== arr.lastIndexOf(x), the element has at least two occurrences. The example below uses this principle inside a loop to build a list of duplicate values while avoiding repeated entries in the result.

Detecting duplicate elements

function hasDuplicate(arr) {
  const unique = new Set(arr);
  return unique.size !== arr.length;
}

function findDuplicates(arr) {
  const duplicates = [];
  
  for (let i = 0; i < arr.length; i++) {
    // If current index equals lastIndexOf, it's the last occurrence
    // Check if we've already found this element earlier
    if (arr.indexOf(arr[i]) !== i) {
      if (!duplicates.includes(arr[i])) {
        duplicates.push(arr[i]);
      }
    }
  }
  
  return duplicates;
}

console.log(hasDuplicate([1, 2, 3, 4]));      // false
console.log(hasDuplicate([1, 2, 2, 3]));      // true
console.log(findDuplicates([1, 2, 3, 2, 4])); // [2]

How lastIndexOf() works

lastIndexOf() scans the array backwards, starting from fromIndex (or array.length - 1 if omitted) and moving toward index 0. At each position, it compares the element to searchElement using strict equality (===). As soon as a match is found, it returns that index and stops. If the scan reaches index 0 without a match, it returns -1. This backward scan is what distinguishes it from indexOf(), which scans forward.

NaN limitation

Like indexOf(), lastIndexOf() cannot find NaN because NaN !== NaN. For arrays that may contain NaN, use findLastIndex(Number.isNaN) instead.

Notes

  • Returns -1 when the element is not found
  • Empty arrays always return -1
  • fromIndex does not change which index is returned—it only limits where the search begins

Strict equality and reference types

lastIndexOf() uses strict equality (===) for comparisons. For primitive values this works as expected, but for objects and arrays it only matches the exact same reference — not an object with the same shape. If you need to find the last matching object by value rather than reference, use findLastIndex() with a custom comparison callback instead.

The fromIndex parameter

When fromIndex is provided, the search starts at that position and works backward. A negative fromIndex is treated as array.length + fromIndex. If the computed starting position is less than 0, the method returns -1 immediately without searching. This allows you to search within a specific slice of the array: for example, arr.lastIndexOf(x, arr.length - 2) finds the last occurrence excluding the final element.

See Also