Array XOR (Symmetric Difference)Loading saved progress…

Array XOR (Symmetric Difference)

The symmetric difference of several arrays is the set of values that belong to exactly one of them — everything except the values they share. It is the array-level version of XOR, the "one or the other, but not both" operation, and lodash exposes it as _.xor. You keep the loners and drop anything that shows up in more than one list.

Implement arrayXor(...arrays) that takes any number of arrays and returns a new array of the values appearing in exactly one input array. Duplicates are removed, and the surviving values stay in the order they first appear across the inputs.

Signature

function arrayXor(...arrays) {
  // returns the values that appear in exactly one of the given arrays
}

Examples

arrayXor([2, 1], [2, 3]);
// → [1, 3]   // 2 is in both arrays, so it drops out
arrayXor([1, 2], [4, 2], [2, 3]);
// → [1, 4, 3]   // 2 appears in all three, so it is excluded
arrayXor([1, 1, 2], [2]);
// → [1]   // duplicates inside one array collapse; 2 is shared

Notes

  • Exactly one array — keep a value only if it appears in a single input array. A value in two or more arrays is dropped, even if it appears an odd number of times overall.
  • Dedupe within each array first — repeats inside one array count as one appearance, so [1, 1] contributes the value 1 a single time.
  • Remove duplicates — each kept value appears once in the result.
  • First-appearance order — scan the inputs left to right; a kept value lands where it is first seen, not in sorted order.
  • Equality is SameValueZero — the rule Set and Array.includes use. NaN equals NaN, and 0 equals -0. The number 1 and the string '1' are different values.
  • Variadic — support zero, one, or many arrays. arrayXor() returns []; a single array returns its unique values.
Loading editor…