0 Tage Serie
javascript / intermediate
Snippet

Fortgeschrittene Set-Operationen für Logik-Sammlungen

Neuere Node.js-Versionen unterstützen native Set-Methoden für mathematische Operationen. Dies macht manuelles Filtern oder Bibliotheken wie Lodash für Sammlungslogik überflüssig.

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
Erklärung
1
admins.intersection(editors)
Gibt ein neues Set zurück, das nur Elemente enthält, die in beiden Sets vorhanden sind.
2
admins.difference(editors)
Gibt ein neues Set mit Elementen des ersten Sets zurück, die nicht im zweiten enthalten sind.