Skip to content

JavaScript Set intersection | code

  • by

JavaScript set Intersection (a ∩ b): create a set that contains those elements of set a that are also in a set b. You have to convert the set into an array and use the filter method for it.

To get the intersection of two Sets:

  1. Convert the first Set into an array.
  2. Use the filter() method to iterate over the array.
  3. Use the has() method to check if each value is contained in the second Set.
  4. Convert the array back to a Set.

JavaScript Set intersection

Simple example code converts a to an array, filters the elements, and converts the result to a set.

<!DOCTYPE html>
<html>
<body>
  <script>
    let a = new Set([1,2,3]);
    let b = new Set([4,3,2]);
    let itrs = new Set([...a].filter(x => b.has(x)));
    console.log(itrs)
  </script>
</body>
</html>

Output:

JavaScript Set intersection

Another example

function getIntersection(setA, setB) {
  const intersection = new Set(
    [...setA].filter(element => setB.has(element))
  );

  return intersection;
}

const set1 = new Set(['a', 'b', 'c']);
const set2 = new Set(['a', 'b', 'd', 'e']);

console.log(getIntersection(set1, set2)); // 👉️ {'a', 'b'}

Do comment if you have any doubts or suggestions on this set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *