0 day streak
javascript / intermediate
Snippet

Advanced Set Operations for Collection Logic

Newer versions of Node.js support native Set methods for mathematical operations. This eliminates the need for manual filtering or third-party libraries like Lodash for collection logic.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const admins = new Set(['alice', 'bob']);
const editors = new Set(['bob', 'charlie']);
const intersection = admins.intersection(editors);
// Set(1) { 'bob' }
const diff = admins.difference(editors);
// Set(1) { 'alice' }
const combined = admins.union(editors);
// Set(3) { 'alice', 'bob', 'charlie' }
nodejs
Breakdown
1
admins.intersection(editors)
Returns a new Set containing only elements present in both sets.
2
admins.difference(editors)
Returns a new Set with elements from the first set that are not in the second.