HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Set operations in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptoperationsset

Problem

Mathematical set operations can be easily applied to JavaScript Set objects and arrays. This collection of articles will introduce you to the most common set operations, such as union, intersection and difference.
> [!NOTE]
>
> At the time of writing, native support for this operation is coming to the Set object, yet it's still in the early stages. Make sure to check environment compatibility if you're planning to use the native methods.
The union of two sets is a set containing all elements that exist in any of the two sets at least once. In order to calculate it, you can use the spread operator (...) to convert the Set objects to array and create a new Set from the resulting array.

Solution

const union = (a, b) => new Set([...a, ...b]);

union(new Set([1, 2, 3]), new Set([4, 3, 2]));
// Set(4) { 1, 2, 3, 4 }


>
> At the time of writing, native support for this operation is coming to the Set object, yet it's still in the early stages. Make sure to check environment compatibility if you're planning to use the native methods.
The union of two sets is a set containing all elements that exist in any of the two sets at least once. In order to calculate it, you can use the spread operator (...) to convert the Set objects to array and create a new Set from the resulting array.
The intersection of two sets is a set containing all elements that exist in both sets. In order to calculate it, you can use Array.prototype.filter() and Set.prototype.has() to filter out all elements that don't exist in the second set.
The difference of two sets is a set containing all elements that exist in the first set but not in the second set. In order to calculate it, you can use the same approach as the intersection, but negating the result of Set.prototype.has().
The symmetric difference of two sets is a set containing all elements that exist in either of the sets but not in both. In order to calculate it, you can calculate the difference of each set with the other and then calculate the union of the two results.

Code Snippets

const union = (a, b) => new Set([...a, ...b]);

union(new Set([1, 2, 3]), new Set([4, 3, 2]));
// Set(4) { 1, 2, 3, 4 }
const intersection = (a, b) => new Set([...a].filter(x => b.has(x)));

intersection(new Set([1, 2, 3]), new Set([4, 3, 2]));
// Set(2) { 2, 3 }
const difference = (a, b) => new Set([...a].filter(x => !b.has(x)));

difference(new Set([1, 2, 3]), new Set([4, 3, 2]));
// Set(1) { 1 }

Context

From 30-seconds-of-code: array-set-operations

Revisions (0)

No revisions yet.