How Lodash _.invertBy Handles Duplicate Values
This article explains how the _.invertBy method in the
Lodash JavaScript library behaves when multiple keys share the same
value. While standard inversion methods typically overwrite duplicate
values, _.invertBy resolves collisions by grouping all
original keys associated with that value into an array. Below, you will
find a direct explanation of this mechanism, a comparison with
_.invert, and a practical code demonstration.
When multiple keys in an object share the same value, Lodash's
_.invertBy does not overwrite previous entries. Instead, it
collects every key that maps to that shared value and stores them inside
an array under the inverted key.
This behavior solves a common issue found in Lodash’s standard
_.invert function. In _.invert, if two keys
hold the same value, the last key processed silently overwrites any
earlier ones, causing data loss. _.invertBy prevents this
loss by ensuring all corresponding keys are preserved as strings inside
an array.
Code Example
Consider the following object where both a and
c share the value 1:
const _ = require('lodash');
const usersByRole = {
a: 1,
b: 2,
c: 1,
d: 3
};
const result = _.invertBy(usersByRole);
console.log(result);
// Output:
// {
// '1': ['a', 'c'],
// '2': ['b'],
// '3': ['d']
// }In this output, the inverted key '1' contains the array
['a', 'c']. The order of keys inside the array reflects the
order in which the object's properties were enumerated during
traversal.
Custom Iteratee Handling
_.invertBy also accepts a custom iteratee function as
its second argument, allowing you to transform the values before
grouping. If the iteratee returns identical keys for different original
values, _.invertBy applies the same grouping rule:
const scores = {
playerOne: 10.2,
playerTwo: 10.8,
playerThree: 20.1
};
// Group by rounded score
const grouped = _.invertBy(scores, Math.floor);
console.log(grouped);
// Output:
// {
// '10': ['playerOne', 'playerTwo'],
// '20': ['playerThree']
// }In all scenarios, whenever a duplicate value or duplicate iteratee
result occurs, _.invertBy safely groups all matching keys
into an array.