DEV Community

Cover image for Operations between sets with JavaScript
Daniel Zotti
Daniel Zotti

Posted on

Operations between sets with JavaScript

Have you ever dealt with operations between sets in JavaScript, such as union, intersection or difference?

Here some ideas of implementation:

Union

Union operation

with arrays

const union = arr1.concat(arr2);
// OR
const union = [...arr1, ...arr2];
Enter fullscreen mode Exit fullscreen mode

with sets

const union = new Set([...set1, ...set2]);
Enter fullscreen mode Exit fullscreen mode

Intersection

Intersecion operation

with arrays

const intersection = arr1.filter(x => arr2.includes(x));
Enter fullscreen mode Exit fullscreen mode

with sets

const intersection = new Set([...set1].filter(x => set2.has(x)));
Enter fullscreen mode Exit fullscreen mode

Difference (from A to B)

Difference operation

with arrays

const difference = arr1.filter(x => !arr2.includes(x))
Enter fullscreen mode Exit fullscreen mode

with sets

const difference = new Set([...set1].filter(x => !set2.has(x)));
Enter fullscreen mode Exit fullscreen mode

Symmetric Difference

Symmetric operation

with arrays

const symmetricDifference = arr1
           .filter(x => !arr2.includes(x))
           .concat(arr2.filter(x => !arr1.includes(x)))
Enter fullscreen mode Exit fullscreen mode

with sets

const symmetricDifference = new Set([...set1]
           .filter(x => !set2.has(x))
           .concat([...set2].filter(x => !set1.has(x))))
Enter fullscreen mode Exit fullscreen mode

Demo

Have a look at this simple Stackblitz demo to play with the examples.

Top comments (0)