array excludes?

I would like to print all values that are not shared between two arrays. Reading
MDN docs on Array.includes, I can easily arrive at a list of shared values:

let array1 = [`James`,`Bill`,`Aaron`,`Trevor`,`Trevor`]
let array2 = [`Aaron`,`James`,`Bill`,`Mike`,`Charles`]

intersection = array2.filter(element => array1.includes(element))`
// returns ["Aaron", "James", "Bill"]

But how to reverse this?

Something like:
outersection = array2.filter(element => array1.excludes(element))
which would return [“Trevor”, “Charles”]?

… Ideally this ‘exclusion’ would also match the data back to the source array:
unique in array1 = “Trevor”; uniquie in array2= “Charles”

Any tricks?

Here’s a sandbox notebook:

Would this work for you?

function excludedValues(arr1, arr2) {
  const excluded1 = arr1.filter(element => !arr2.includes(element))
  const excluded2 = arr2.filter(element => !arr1.includes(element))
  return excluded1.concat(excluded2)
}
1 Like

That’s it! So putting an ! in front of the array turns inclusion to exclusion? Neat.

I didn’t see this in the docs. How did you learn how this works? … Even clicking into ECMA-262 and searching for !, this isn’t super apparent (and there are 662 instances of !).

! is just the Boolean “NOT” operator which turns true to false and vice versa (it’s actually more complicated because JS has rules about what converts to true and what converts to false). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

Thanks @bgchen. I’ve seen this in the context of filter matching. I would never have guessed I could prepend it to the array and it would inverse the logic of the operation… but it is logical :wink:

1 Like