Aller au contenu principal

xor()

xor<T>(arrays): T[]

Creates an array of unique values that is the symmetric difference of the given arrays.

remarque

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

FunctionReturns
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"]