Lodash _.xorBy() method
What you’ll learn
Prerequisites
Understand _.xor() first; xorBy keeps the same symmetric-difference idea but compares iteratee outputs instead of whole values.
- You can describe a stable projection key such as
idorMath.floor(value). - You can open Try-it labs or run snippets locally.
Overview
_.xorBy is useful when payloads differ structurally but collide on business keys—inventory by SKU, records by id, or numeric buckets by floor/round projections.
Syntax
_.xorBy(...arrays, iteratee)- arrays: two or more collections to compare symmetrically.
- iteratee: function/string/path used to project a comparison key for each element.
- Returns: new array of elements whose projected keys are exclusive after xor folding.
Objects by id
Shared ids cancel even if object payload fields differ.
import xorBy from "lodash/xorBy";
xorBy(
[{ id: 1, name: "a" }, { id: 2, name: "b" }],
[{ id: 2, extra: true }, { id: 3, name: "c" }],
"id"
);
// → [{ id: 1, name: "a" }, { id: 3, name: "c" }]Numbers by Math.floor
Buckets that appear on both sides cancel; exclusive buckets survive.
import xorBy from "lodash/xorBy";
xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// → [1.2, 3.4]Three arrays, one iteratee
XOR folding continues across each additional array, still keyed by iteratee output.
import xorBy from "lodash/xorBy";
xorBy([{ x: 1 }, { x: 2 }], [{ x: 2 }, { x: 3 }], [{ x: 3 }, { x: 4 }], "x");
// → [{ x: 1 }, { x: 4 }]📋 _.xorBy vs xor, xorWith, differenceBy
| API | Equality signal | Best when |
|---|---|---|
_.xorBy(...arrays, iteratee) | Projected key | Exclusive merge on id/path/math buckets |
_.xor(...arrays) | Whole value SameValueZero | Primitive arrays or stable references |
_.xorWith(...arrays, comparator) | Comparator | Pairwise deep/custom equality |
_.differenceBy(array, ...values) | Projected key | Directional subtraction from first array only |
Pitfalls to avoid
Iteratee placement
The iteratee must be the final argument, after all arrays.
Unstable projections
Random/non-deterministic keys break xor logic; use stable fields or pure transforms.
Need comparator, not key
If equality needs pairwise logic, use xorWith.
❓ FAQ
Summary
- Purpose:
_.xorBy(...arrays, iteratee)keeps values whose projected keys are exclusive. - Contrast: downgrade to xor for whole-value comparisons or switch to xorWith for comparator logic.
- Next: Lodash _.xorWith(), _.xor() (previous), or the array methods hub.
Think of xorBy as _.xor() on projected keys—great when whole objects differ but a field like id should decide exclusivity.
6 people found this page helpful
