Have you ever dealt with operations between sets in JavaScript, such as union, intersection or difference?
Here some ideas of implementation:
Union
with arrays
const union = arr1.concat(arr2);
// OR
const union = [...arr1, ...arr2];
with sets
const union = new Set([...set1, ...set2]);
Intersection
with arrays
const intersection = arr1.filter(x => arr2.includes(x));
with sets
const intersection = new Set([...set1].filter(x => set2.has(x)));
Difference (from A to B)
with arrays
const difference = arr1.filter(x => !arr2.includes(x))
with sets
const difference = new Set([...set1].filter(x => !set2.has(x)));
Symmetric Difference
with arrays
const symmetricDifference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)))
with sets
const symmetricDifference = new Set([...set1]
.filter(x => !set2.has(x))
.concat([...set2].filter(x => !set1.has(x))))
Demo
Have a look at this simple Stackblitz demo to play with the examples.
Top comments (0)