Exclusive OR

JavaScript

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']

More fire tips

Splitting arrays into chunks

By combining map and slice, we can write a helper function to split large arrays into many similarly sized blocks. This is useful for features like pagination.

JavaScript
Read fire tip

Read all fire tips →