Lodash sortedLastIndexOf Return Value When Absent
This article explains what Lodash's _.sortedLastIndexOf
method returns when searching for a value that does not exist within a
sorted array. It details the exact return value, highlights the critical
distinction between this function and _.sortedLastIndex,
and provides practical JavaScript code examples to demonstrate its
behavior in production code.
The Return Value for Absent Elements
When a target value is not found in the provided array,
_.sortedLastIndexOf returns -1.
Because it mirrors the behavior of standard JavaScript search methods
like Array.prototype.lastIndexOf, it strictly signals
non-existence by returning -1 rather than indicating an
insertion point or throwing an error.
const _ = require('lodash');
const numbers = [10, 20, 30, 30, 40, 50];
// Searching for a value that exists
console.log(_.sortedLastIndexOf(numbers, 30));
// Output: 3 (the highest index of 30)
// Searching for a value that is absent
console.log(_.sortedLastIndexOf(numbers, 25));
// Output: -1_.sortedLastIndexOf
vs. _.sortedLastIndex
A common source of confusion in Lodash is the distinction between
_.sortedLastIndexOf and _.sortedLastIndex.
While their names are nearly identical, their handling of missing values
differs significantly:
_.sortedLastIndexOf: Performs a binary search for the element. If the value exists, it returns the highest index where the value appears. If the value does not exist, it returns-1._.sortedLastIndex: Calculates the highest index at which the value should be inserted to maintain the sorted order of the array. It never returns-1, even if the element is absent.
const numbers = [10, 20, 30, 40];
// Value is absent
console.log(_.sortedLastIndexOf(numbers, 25)); // Output: -1
console.log(_.sortedLastIndex(numbers, 25)); // Output: 2Important Considerations
To ensure _.sortedLastIndexOf reliably returns
-1 for absent values, the input array must be sorted in
ascending order. The method uses a binary search algorithm
(O(log n) time complexity). If the array is unsorted, the
binary search logic will fail, potentially returning -1 for
values that are actually present or returning incorrect indices.