JavaScript Program to Illustrate Different Set Operations

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example 1: Set Union Operation

Output

Set {"apple", "mango", "orange", "grapes", "banana"}

The set union operation combines elements of both sets into one.

A new set unionSet is created using new Set(). The unionSet variable contains all the values of setA. Then, the for...of loop is used to iterate through all the elements of setB and add them to unionSet using the add() method.

The set does not contain duplicate values. Hence, if the set contains the same value, the latter value is discarded.


Example 2: Set Intersection Operation

Output

Set {"apple"}

The set intersection operation represents elements that are present in both setA and setB.

A new set intersectionSet is created using new Set(). Then, the for...of loop is used to iterate through the setB. For every element that is present in both setA and setB, they are added to the intersection set.


Example 3: Set Difference Operation

Output

Set {"mango", "orange"}

The set difference operation represents elements that are present in one set and not in another set.

The differenceSet contains all the elements of setA. Then, the for...of loop is used to iterate through all the elements of setB. If the element that is present in setB is also available in setA, that element is deleted using delete() method.


Example 4: Set Subset Operation

Output

true

The set subset operation returns true if all the elements of setB are in setA.

The for...of loop is used to loop through the elements of setB. If any element that is present is setB is not present in setA, false is returned.