One of the basic `Set`

operations is to get the intersection of two sets. In mathematical terms, this is expressed as `A ∩ B`

(i.e. elements that are common in both "A" and "B").

To get the intersection of two JavaScript `Set`

objects, you can loop over one of the `Set`

objects, and check which elements are common between the two by using the `Set.prototype.has()`

method on the other `Set`

. For example:

function intersection(setA, setB) { const result = new Set(); for (const elem of setA) { if (setB.has(elem)) { result.add(elem); } } return result; } const setA = new Set([1, 2, 3, 4]); const setB = new Set([3, 4, 5, 6]); console.log(intersection(setA, setB)); // Set(2) {3, 4}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.