The Set object has a few new methods that can simplify tasks for comparing sets and arrays.
Set.prototype.difference
For two sets, A and B, returns the elements that are in A but not B.
For example:
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);
console.log(setA.difference(setB)); // Set(2) {1,2}
Set.prototype.union
For two sets, A and B, return all elements in both sets:
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([0, 2, 4, 5]);
console.log(setA.union(setB)); // Set(6) {1,2,3,4,0,5}
console.log(Array.from(setA.union(setB)).sort());
[0, 1, 2, 3, 4, 5];
Set.prototype.intersection
For two sets, A and B, return the elements common to both sets:
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([0, 2, 4, 5]);
console.log(setA.intersection(setB)); // Set(2) {2,4}
Set.prototype.isSubsetOf
For two sets, A and B, return true or false if set A is a subset of set B:
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([0, 1, 2, 3, 4, 5]);
console.log(setA.isSubsetOf(setB)); // true
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([0, 1, 2, 3]);
console.log(setA.isSubsetOf(setB)); // false
Set.prototype.isSupersetOf
For two sets, A and B, return true or false if set A is a superset of set B:
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([1, 2]);
console.log(setA.isSupersetOf(setB)); // true
Set.prototype.symmetricDifference
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 3, 4, 5]);
console.log(setA.symmetricDifference(setB)); // Set(2) { 1, 5}