Lodash _.xorBy Explained: Compare Array Values

The _.xorBy method in the Lodash JavaScript library computes the symmetric difference between multiple arrays based on a criterion determined by an iteratee function. Unlike standard difference operations, it identifies elements that are present in one array or another, but not in both, using a transformation or property extraction to evaluate equality. This article explains how _.xorBy works, its syntax, and how to use it with practical code examples.

What is _.xorBy?

In mathematics and programming, a symmetric difference (exclusive OR / XOR) between sets yields elements that belong to either set, but not to their intersection. Lodash provides the base _.xor function for simple, direct comparisons.

The _.xorBy method extends this capability by accepting an "iteratee." Before performing the comparison, Lodash invokes this iteratee on each element of the input arrays. This generates a computed value used exclusively for comparison, though the final returned array contains the original elements that produced the unique values.

Syntax

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

Example 1: Comparing Transformed Primitives

When working with numbers, you may want to compare values after applying a mathematical function like Math.floor:

const _ = require('lodash');

const array1 = [2.1, 1.2];
const array2 = [2.3, 3.4];

const result = _.xorBy(array1, array2, Math.floor);
// Output: [1.2, 3.4]

In this case:

  1. array1 floored values are [2, 1].
  2. array2 floored values are [2, 3].
  3. The value 2 appears in both arrays, so 2.1 and 2.3 are excluded.
  4. The remaining unique values are returned: 1.2 and 3.4.

Example 2: Comparing Objects by Property

A common use case for _.xorBy is comparing collections of objects based on a specific property, such as an id.

const _ = require('lodash');

const currentUsers = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

const newUsers = [
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const result = _.xorBy(currentUsers, newUsers, 'id');
/*
Output:
[
  { id: 1, name: 'Alice' },
  { id: 3, name: 'Charlie' }
]
*/

Lodash compares the objects solely by their id property. Because the object with id: 2 appears in both arrays, it is filtered out, leaving only the unique records from each set.

Key Behaviors to Remember