xor()
xor<
T>(arrays):T[]
Creates an array of unique values that is the symmetric difference of the given arrays.
Returns values from all arrays that appear in exactly one array.
Type Parametersโ
T: Tโ
The type of elements in the arrays.
Parametersโ
arrays: readonly (readonly T[])[]โ
The arrays to inspect.
Returns: T[]โ
A new array of filtered values.
Sinceโ
2.0.0
Performanceโ
O(n) โ uses Map for counting occurrences across arrays.
Also known asโ
symmetricDifference (Remeda, Ramda) ยท xor (Lodash, es-toolkit) ยท โ (Radashi, Effect, Modern Dash, Antfu)
Exampleโ
xor([[2, 1], [2, 3]]);
// => [1, 3]
xor([[1, 2, 3], [3, 4, 5], [5, 6]]);
// => [1, 2, 4, 6]
How it works?โ
Symmetric difference โ returns values that appear in exactly one array. Values present in multiple arrays are excluded.
Count occurrencesโ
xor vs difference vs intersectionโ
| Function | Returns |
|---|---|
difference(a, b) | In A but not B |
intersection(a, b) | In both A and B |
xor([a, b]) | In A or B, but not both |
Use Casesโ
Find items unique to each array ๐โ
Get elements that exist in one array but not both (symmetric difference). Perfect for comparing lists and finding discrepancies.
const listA = ["apple", "banana", "cherry"];
const listB = ["banana", "cherry", "date"];
const uniqueToEach = xor(listA, listB);
// => ["apple", "date"]
Detect changes between snapshotsโ
Find what was added or removed between two states. Useful for tracking modifications or generating changelogs.
const before = ["user1", "user2", "user3"];
const after = ["user2", "user3", "user4"];
const changes = xor(before, after);
// => ["user1", "user4"] (user1 removed, user4 added)
Compare feature setsโ
Find features unique to each plan or version. Essential for plan comparison or feature matrices.
const basicPlan = ["storage", "email", "support"];
const proPlan = ["storage", "email", "analytics", "api"];
const differences = xor(basicPlan, proPlan);
// => ["support", "analytics", "api"]