Skip to content

Instantly share code, notes, and snippets.

@clohr
Created February 26, 2017 19:09
Show Gist options
  • Save clohr/44d4aa6fb749b3abd4e7fcde82e03d29 to your computer and use it in GitHub Desktop.
Save clohr/44d4aa6fb749b3abd4e7fcde82e03d29 to your computer and use it in GitHub Desktop.
ES6 Sets: Intersection, Difference, and Union
const a = new Set([1, 2, 3, 4, 4, 4])
const b = new Set([3, 4, 5, 6])
const intersect = (set1, set2) => [...set1].filter(num => set2.has(num))
const differ = (set1, set2) => [...set1].filter(num => !set2.has(num))
const joinSet = (set1, set2) => [...set1, ...set2]
const myIntersectedSet = new Set(intersect(a, b))
console.log('myIntersectedSet', myIntersectedSet)
const myDifferenceSet = new Set(differ(a, b))
console.log('myDifferenceSet', myDifferenceSet)
const myJoinedSet = new Set(joinSet(a, b))
console.log('myJoinedSet', myJoinedSet)
@clohr
Copy link
Author

clohr commented Feb 26, 2017

Creating a set from an existing array will remove duplicates automatically. Then, you can use the spread operator to destructure the original sets to create unions, intersections, and differences.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment