Lodash sortedIndexBy Transformer Explained
In the Lodash JavaScript library, _.sortedIndexBy uses
an iteratee function as its transformer to compute the sort
representation of values during a binary search. This article explains
how the iteratee transformer works within _.sortedIndexBy,
what default transformer is applied, and how custom transformers dictate
the insertion index of an element in a sorted array.
The Iteratee Transformer
The transformer applied by _.sortedIndexBy is referred
to as the iteratee. Its purpose is to transform both
the items in the existing array and the target value into comparable
values before evaluating their sorted order.
By default, the transformer applied is _.identity. When
no iteratee is specified, Lodash returns the first argument passed to it
without alteration:
// Default transformer behavior
const iteratee = _.identity; // (value) => valueHow the Transformation Works
When calling
_.sortedIndexBy(array, value, [iteratee=_.identity]),
Lodash performs a binary search to find the lowest index where
value should be inserted to maintain the array's sorted
order.
During this search:
- Lodash applies the iteratee transformer to the target
value. - Lodash applies the same iteratee transformer to the array elements as they are inspected during the binary search.
- The transformed values are compared using standard relational
operators (
<) to determine ordering.
Types of Transformers Supported
Lodash automatically normalizes the iteratee argument through its
internal baseIteratee method, allowing different
transformation patterns:
- Custom Function: You can provide a function
(item) => transformedValue. For example,(o) => o.xtransforms each object into the value of itsxproperty. - Property Name (Shorthand): Supplying a string like
'age'causes Lodash to use_.property('age'), transforming each object into the value of its specified property path.
Example
const objects = [{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }];
// Using a property name transformer
_.sortedIndexBy(objects, { 'x': 40 }, 'x');
// => 2
// Using a function transformer
_.sortedIndexBy(objects, { 'x': 40 }, (o) => o.x);
// => 2In this example, the transformer extracts the numerical value of
x for both the array items and the target object, allowing
the algorithm to correctly place { 'x': 40 } at index
2.