Skip to content

JavaScript Set union

  • by

JavaScript union (ab): create a set that contains the elements of both sets a and set b. To get a union of two Sets, use the spread syntax (…) to unpack the values of the Sets into an array and pass the result to the Set() constructor.

new Set([...set1, ...set2])

The new Set will contain the union of the other two.

JavaScript Set union

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
   let a = new Set([10,20,30]);
   let b = new Set([40,30,20]);
   
   let union = new Set([...a, ...b]);

   console.log(union)
 </script>
</body>
</html>

Output:

JavaScript Set union

We used the spread syntax (…) to unpack the values from the two Set objects into an array.

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

const arr = [...set1, ...set2];

console.log(arr); // 👉️ ['a', 'b', 'c' ,'a', 'b', 'd']

Get a Union of Two Sets using for-of loop

function getUnion(setA, setB) {
  const union = new Set(setA);

  for (const element of setB) {
    union.add(element);
  }

  return union;
}

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

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

Do comment if you have any doubts or suggestions on this JS 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading