Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

Union, Intersection, and Difference of Set in javascript

πŸ”₯ Union of Set

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

Usage

const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);

const un = union(a, b);
// Set(4) {1, 2, 3, 4}

πŸ”₯ Intersection of Set

const intersection = (a, b) => new Set([...a].filter((v) => b.has(v)));

Usage

const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);

const int = intersection(a, b);
// Set(2) {2, 3}

πŸ”₯ Difference of Set

const difference = (a, b) => new Set([...a].filter((v) => !b.has(v)));

Usage

const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);

const differenceA = difference(a, b);
// Set(1) {1}
const differenceB = difference(b, a);
// Set(1) {4}

πŸ“š References