Created
June 16, 2021 12:14
-
-
Save jfollmann/b065d1ebb9043cacfbe9249a572bbd7e to your computer and use it in GitHub Desktop.
Array intersection, difference, and union in ES6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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