DEV Community

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

Posted on

2

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)