Exclusive OR

Finding values that exist in only one of two arrays is called “XOR”, or “exclusive OR”. It gets us all values that appear in either the first OR the second array, but not both.

// takes two arrays and returns all elements that appear in only one of them
const xor = (first, second) => [
  ...first.filter(element => !second.includes(element)),
  ...second.filter(element => !first.includes(element))
]

// `xor` returns all elements that appear in only one of the two arrays
xor([1, 2, 3, 4, 5], [2, 3, 4, 5, 6])   // ⇒ [1, 6]

// an element can appear multiple times, but only in one array
xor(['beep', 'beep', 'boo', 'boo'], ['beep'])  // ⇒ ['boo', 'boo']

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.