JS Sets - Intersection
Extended demo to include sets of objects.
by Ben Clayton
HTML
Intersection of Sets - look for output in Developer tools Console.
<br>
Useful ref docs:<br>
<a href="https://2ality.com/2015/01/es6-set-operations.html" target="_blank">https://2ality.com/2015/01/es6-set-operations.html</a>
JavaScript
// Set of numbers
let a1 = new Set([1, 2, 3]);
let b1 = new Set([4, 3, 2]);
let intersection1 = new Set(
[...a1].filter(x => b1.has(x)));
console.log(a1, b1, intersection1)
//---------------------------------------
// set of Strings
let a2 = new Set(['A', 'B','C']);
let b2 = new Set(['B', 'C', 'D']);
let intersection2 = new Set(
[...a2].filter(x => b2.has(x)));
console.log(a2, b2, intersection2)
//---------------------------------------
// Set of objects (checks 'name' property for value)
let a3 = new Set([{name:"A"},{name:"B"},{name:"C"}]);
let b3 = new Set([{name:"B"}, {name:"C"}, {name:"D"}]);
let intersection3 = new Set(
[...a3].filter(
x => Array.from(b3).filter(y => x.name == y.name).length));
console.log(a3, b3, intersection3)