Skip to content

Instantly share code, notes, and snippets.

@jfollmann
Created June 16, 2021 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jfollmann/b065d1ebb9043cacfbe9249a572bbd7e to your computer and use it in GitHub Desktop.
Save jfollmann/b065d1ebb9043cacfbe9249a572bbd7e to your computer and use it in GitHub Desktop.
Array intersection, difference, and union in ES6
const arrA = [1, 3, 4, 5];
const arrB = [1, 2, 5, 6, 7];
const intersection = arrA.filter((x) => arrB.includes(x));
console.log('intersection', intersection);
// Output => intersection [ 1, 5 ]
const differenceA = arrA.filter((x) => !arrB.includes(x));
console.log('differenceA', differenceA);
// Output => difference [ 3, 4 ]
const differenceB = arrB.filter((x) => !arrA.includes(x));
console.log('differenceB', differenceB);
// Output => difference [ 2, 6, 7 ]
const symmetricalDifference = arrA
.filter((x) => !arrB.includes(x))
.concat(arrB.filter((x) => !arrA.includes(x)));
console.log('symmetricalDifference', symmetricalDifference);
// Output => symmetricalDifference [ 3, 4, 2, 6, 7 ]
const union = [...arrA, ...arrB];
console.log('union', union);
// Output => union [1, 3, 4, 5, 1,2, 5, 6, 7]
const unionWithoutDuplications = [...new Set([...arrA, ...arrB])];
console.log('unionWithoutDuplications', unionWithoutDuplications);
// Output => unionWithoutDuplications [1, 3, 4, 5, 2, 6, 7]
// Reference https://medium.com/@alvaro.saburido/set-theory-for-arrays-in-es6-eb2f20a61848
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment