Lodash _.xor() method
What you’ll learn
- How
_.xor(...arrays)keeps elements that appear exclusively after symmetric difference folding. - Why duplicates toggle membership counts and can cancel unexpectedly.
- When _.difference(), _.union(), _.intersection(), or _.xorBy() expresses the intent more directly.
- Try each example in the editor (
?tryit=1,2,3) with Lodash from a CDN.
Prerequisites
Know _.difference() subtracts later arrays from the first operand—xor removes that directional bias entirely.
- You can read Venn diagrams with exclusive regions shaded.
- You can open Try-it labs or run snippets locally.
Overview
_.xor helps diff feature flags, reconcile polling snapshots, or isolate IDs that flipped between imports—anything where neither side should dominate the filter.
Symmetric cut
Shared keys cancel; leftovers from any operand bubble outward.
Toggle semantics
Repeated occurrences flip parity—expect surprises when duplicates abound.
Immutable inputs
Sources remain reusable for downstream merges or auditing.
Syntax
_.xor(...arrays) - arrays: two or more collections (array-like arguments flatten predictably like other Lodash set helpers).
- Returns: new array containing symmetric-difference survivors ordered by Lodash merge rules.
Classic two-array exclusive merge
Overlapping entries cancel—only numbers unique to a single operand survive.
import xor from "lodash/xor";
xor([2, 1], [2, 3]);
// → [1, 3] Three-way symmetric difference
Each additional array continues folding XOR logic—elements appearing across lists an odd number of times survive.
import xor from "lodash/xor";
xor([1, 2], [2, 3], [3, 4]);
// → [1, 4] NaN parity like other values
Because Lodash uses SameValueZero, duplicate NaN placeholders behave predictably when aligning noisy datasets.
import xor from "lodash/xor";
xor([NaN, 1], [NaN, 2]);
// → [1, 2] 📋 _.xor vs difference, union, intersection
| API | Shape | Use case |
|---|---|---|
_.xor(...arrays) | Symmetric difference | Exclusive-or filtering across peers |
_.difference(array, ...others) | Directed subtraction | Primary feed minus blacklist arrays |
_.union(...arrays) | Coverage union | Keep every distinct element ever seen |
_.intersection(...arrays) | Overlap core | Require presence in every operand |
Pitfalls to avoid
Duplicate toggling
Repeated identical values inside one array flip parity—run _.uniq() first when you intend pure set semantics.
Expecting directionality
Need “everything in A unless also in B”? That is difference, not xor.
❓ FAQ
Summary
- Purpose:
_.xor(...arrays)emits elements exclusive to the symmetric difference of its operands. - Contrast: switch to difference for asymmetric subtraction.
- Next: Lodash _.xorBy(), _.without() (previous), or the array methods hub.
Symmetric difference answers “what appears in an odd number of lists?” for membership toggling—pair it mentally with _.difference() when you only subtract from a primary array.
6 people found this page helpful
