Lodash lastIndexOf with Duplicate Elements

The _.lastIndexOf method in the Lodash JavaScript library is designed to locate the index of a specified value within an array by searching from right to left. When dealing with arrays containing duplicate elements, _.lastIndexOf resolves the duplicates by returning the highest index where the target value appears, effectively identifying its final occurrence. This article explains the reverse-traversal mechanism used for duplicate elements, demonstrates how the optional fromIndex parameter alters the search boundaries, and provides straightforward code examples.

How Reverse Traversal Resolves Duplicates

Standard search methods like _.indexOf iterate from index 0 upward, returning the first occurrence of a value. In contrast, _.lastIndexOf iterates backwards starting from the last element (array.length - 1).

Because the algorithm terminates as soon as it finds a match, it will always return the index of the duplicate element closest to the end of the array. Any preceding duplicate values located at lower indices are ignored.

const _ = require('lodash');

const numbers = [10, 20, 30, 20, 40, 20, 50];

// The value 20 appears at indices 1, 3, and 5
const result = _.lastIndexOf(numbers, 20);

console.log(result); 
// Output: 5

In this example, although 20 exists at multiple positions, _.lastIndexOf returns 5 because it encounters that position first when reading the array from right to left.

Targeting Earlier Duplicates Using fromIndex

You can control where the reverse search begins by providing the third argument, fromIndex. When specified, _.lastIndexOf starts its backward search from that specific index rather than the end of the array.

This parameter allows you to locate duplicate occurrences that appear earlier in the array:

const items = ['a', 'b', 'c', 'b', 'd'];

// Start searching backwards from index 2
const result = _.lastIndexOf(items, 'b', 2);

console.log(result); 
// Output: 1

By setting fromIndex to 2, the search ignores the duplicate 'b' at index 3 and instead returns index 1.

If fromIndex is negative, Lodash treats it as an offset from the end of the array:

// A fromIndex of -3 corresponds to index 2 in an array of length 5
const negativeOffsetResult = _.lastIndexOf(items, 'b', -3);

console.log(negativeOffsetResult); 
// Output: 1

Value Comparison Standard

Lodash uses the SameValueZero comparison algorithm for _.lastIndexOf. This means duplicates are evaluated using strict equality (===), with the exception that NaN is treated as equal to NaN.

const values = [NaN, 1, 2, NaN, 3];

console.log(_.lastIndexOf(values, NaN));
// Output: 3

If a duplicate value does not match by strict equality (such as two distinct object references containing identical properties), _.lastIndexOf will not treat them as matches. In such cases, _.findLastIndex with a custom predicate should be used instead.