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])[arrays](Array): The arrays to inspect.[iteratee=_.identity](Function|string): The iteratee invoked per element to generate the criterion by which uniqueness is decided.
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:
array1floored values are[2, 1].array2floored values are[2, 3].- The value
2appears in both arrays, so2.1and2.3are excluded. - The remaining unique values are returned:
1.2and3.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
- Preserves Original Items: The returned array contains the original values, not the results returned by the iteratee.
- Result Order: The order of the returned elements is determined by the order in which they appear in the original arrays.
- Multiple Arrays: You can pass more than two arrays
into
_.xorBy, with the iteratee placed as the final argument.