A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/how-to-perform-intersection-of-two-sets-in-javascript/ below:

How to perform intersection of two sets in JavaScript ?

How to perform intersection of two sets in JavaScript ?

Last Updated : 23 Jul, 2025

An intersection of two sets means the element which occurs in both sets. In mathematical terms, the intersection of two sets is shown by A ∩ B. It means all the elements which is common in set A and set B should occur in a single array. In javascript, the intersection of two sets means getting the common from both sets.

We can find the intersection of two sets in many ways:

Using Sets & has() Method: A set is a collection of items that are unique i.e no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. A set can store any type of value whether primitive or objects.

Example 1: In this example, we will see the intersection of sets by using the set.has() method.

JavaScript
function getIntersection(set1, set2) {
    const ans = new Set();
    for (let i of set2) {
        if (set1.has(i)) {
            ans.add(i);
        }
    }
    return ans;
}
const set1 = new Set([1, 2, 3, 8, 11]);
const set2 = new Set([1, 2, 5, 8]);

const result = getIntersection(set1, set2);
console.log(result);

Output:

Set(3) { 1, 2, 8 }

Using the has() & filter() Method: We check if the element is present in set1 also then we are going to add that element to the new set. 

Example 2: In this example, we will see the intersection of sets by using the filter() method. We have also used the spread operator for separating the element.

JavaScript
let set1 = new Set([1, 2, 3]);
let set2 = new Set([4, 3, 2]);
let set = new Set([...set1].filter(x => set2.has(x)));
console.log(set);

Output:

Set(2) { 2, 3 }


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4