How Lodash intersectionBy Applies Transformers

Lodash's _.intersectionBy method computes the common elements across multiple arrays by applying an "iteratee" (transformer) to each element before performing comparison checks. This article explains how the method extracts the transformer, maps input data to comparable values using functions or property paths, and returns the original, untransformed values from the first array that match across all provided datasets.

Syntax and Core Mechanics

The _.intersectionBy function accepts one or more arrays, followed by an iteratee as the final argument:

_.intersectionBy([arrays], [iteratee=_.identity])

When called, Lodash inspects the arguments to separate the target arrays from the transformer. The transformation process follows a distinct execution flow:

  1. Iteratee Resolution: Lodash converts the specified iteratee into a callable function using its internal baseIteratee utility. If a string is provided, it acts as a property accessor. If a function is passed, it executes directly. If omitted, it defaults to _.identity.
  2. Criteria Mapping: Each element in the provided arrays is processed through the iteratee to generate a secondary value, known as a comparison criterion.
  3. Comparison Check: Lodash compares the generated criteria across the arrays using the SameValueZero algorithm (similar to strict equality ===, but treats NaN as equal to NaN).
  4. Value Retention: When a match is found based on the transformed criteria, Lodash retains and outputs the original element from the first array, discarding the transformed representation.

Transforming with a Function

When a function is provided as the iteratee, Lodash passes each array item into that function as a single argument. The return value of that function is then used for the intersection comparison.

const numbers1 = [2.1, 1.2, 3.4];
const numbers2 = [2.3, 4.5, 1.8];

const result = _.intersectionBy(numbers1, numbers2, Math.floor);
// Output: [2.1, 1.2]

In this example:


Transforming with Property Shorthands

Lodash allows strings or property paths to act as iteratees. When a string is passed, Lodash wraps it in _.property, fetching that specific key from each object prior to comparison.

const usersA = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const usersB = [{ id: 2, name: 'Bobby' }, { id: 3, name: 'Charlie' }];

const commonUsers = _.intersectionBy(usersA, usersB, 'id');
// Output: [{ id: 2, name: 'Bob' }]

During this process:

  1. usersA transforms to [1, 2] using the id property.
  2. usersB transforms to [2, 3].
  3. The common identifier is 2.
  4. The result yields { id: 2, name: 'Bob' }, preserving the original object reference from usersA.

Key Characteristics to Keep in Mind