How Lodash sortedLastIndexBy Works in JavaScript
This article provides a comprehensive overview of the
_.sortedLastIndexBy method from the Lodash JavaScript
utility library. You will learn what the function does, understand its
syntax and parameters, see practical code examples, and discover how it
differs from similar search methods like
_.sortedIndexBy.
What is
_.sortedLastIndexBy?
The _.sortedLastIndexBy method uses a binary search
algorithm to determine the highest index at which a given
value should be inserted into an already sorted
array in order to maintain its sort order.
Unlike standard index-finding methods that look for exact value
matches, _.sortedLastIndexBy computes a criteria for each
element using an iteratee function. If the value being checked matches
one or more existing elements based on this iteratee, the method returns
the index after the last matching element.
Syntax
_.sortedLastIndexBy(array, value, [iteratee=_.identity])Parameters
array(Array): The sorted array to inspect.value(*): The value to evaluate for insertion.iteratee(Function|string): The iteratee invoked per element to compute the sort criteria. Defaults to_.identity.
Returns
- (number): Returns the highest index at
which
valueshould be inserted intoarray.
Code Examples
Example 1: Using a Property Name Shorthand
When dealing with arrays of objects, you can pass a string representing the object property by which the array is sorted.
const _ = require('lodash');
const users = [
{ 'name': 'Alice', 'age': 25 },
{ 'name': 'Bob', 'age': 30 },
{ 'name': 'Charlie', 'age': 30 },
{ 'name': 'Diana', 'age': 35 }
];
// Determine where to insert a user with age 30
const index = _.sortedLastIndexBy(users, { 'name': 'Eve', 'age': 30 }, 'age');
console.log(index);
// Output: 3In this example, two users already have an age of
30 (indices 1 and 2).
_.sortedLastIndexBy returns index 3, which
places the new entry immediately after the last existing match.
Example 2: Using a Custom Iteratee Function
You can pass a custom function if the sorting logic depends on a computed value.
const _ = require('lodash');
const words = ['apple', 'banana', 'cherry', 'date'];
// The array is sorted by word length: 5, 6, 6, 4?
// Let's sort properly by length first:
const sortedByLength = ['date', 'apple', 'banana', 'cherry'];
// lengths: 4, 5, 6, 6
const newWord = 'orange'; // length 6
const index = _.sortedLastIndexBy(sortedByLength, newWord, function(word) {
return word.length;
});
console.log(index);
// Output: 4Because 'banana' and 'cherry' both have a
length of 6, 'orange' is placed at index 4 (at
the end of the matching group).
_.sortedIndexBy
vs. _.sortedLastIndexBy
The primary distinction between _.sortedIndexBy and
_.sortedLastIndexBy lies in how duplicates are handled:
_.sortedIndexBy: Returns the first (lowest) possible index for insertion._.sortedLastIndexBy: Returns the last (highest) possible index for insertion.
const numbers = [{ x: 10 }, { x: 20 }, { x: 20 }, { x: 30 }];
const target = { x: 20 };
_.sortedIndexBy(numbers, target, 'x'); // Returns 1 (before existing 20s)
_.sortedLastIndexBy(numbers, target, 'x'); // Returns 3 (after existing 20s)Important Considerations
- Pre-sorted Requirement: The input array must already be sorted according to the criteria returned by the iteratee. If the array is unsorted, the binary search algorithm will produce incorrect results.
- Performance: Because it uses binary search, the
time complexity is \(O(\log n)\),
making it significantly faster for large collections compared to linear
search methods like
Array.prototype.findIndex.