I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Exclusive OR across two arrays

Posted on

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"]
// 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"]
Debug
none
Grid overlay