This article illustrates the various operations that can be applied in a set. There are various operations that can be applied on a set that are listed below:
- Union of sets
- Intersection of sets
- Set difference
- Set Subset Operation
Union of sets
A union set is the combination of two elements. In mathematical terms, the union of two sets is shown by A ∪ B. It means all the elements in set A and set B should occur in a single array. In JavaScript, a union set means adding one set element to the other set.
Example:
Javascript
function showUnion(sA, sB) { Â Â Â Â const union = new Set(sA); Â Â Â Â for (const num of sB) { Â Â Â Â Â Â Â Â union.add(num); Â Â Â Â } Â Â Â Â return union; } const s1 = new Set(['1', '6', '8']); const s2 = new Set(['2', '3', '4']); console.log(showUnion(s1, s2)); |
Set(6) { '1', '6', '8', '2', '3', '4' }
Intersection of sets
An intersection of two sets means the element that 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.
Example:
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); |
Set(3) { 1, 2, 8 }
Set difference
Set difference means that the array we subtract should contain all the unique element which is not present in the second array.
Example:
Javascript
let A = [7, 2, 6, 4, 5]; let B = [1, 6, 4, 9]; const set1 = new Set(A); const set2 = new Set(B); Â Â const difference = new Set(); set1.forEach(element => { Â Â Â Â if (!set2.has(element)) { Â Â Â Â Â Â Â Â difference.add(element); Â Â Â Â } }); console.log([...difference]); |
[ 7, 2, 5 ]
Set Subset Operation
The set subset operation returns true if all the elements of setB are in setA.
Example:
Javascript
function subSet(val1, val2) { Â Â Â Â // Get an iterator for val2 Â Â Â Â const iterator = val2.values(); Â Â Â Â Â Â let nextVal = iterator.next(); Â Â Â Â Â Â while (!nextVal.done) { Â Â Â Â Â Â Â Â if (!val1.has(nextVal.value)) { Â Â Â Â Â Â Â Â Â Â Â Â return false; Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â nextVal = iterator.next(); Â Â Â Â } Â Â Â Â Â Â return true; } Â Â // Two sets const val1 = new Set(['HTML', 'CSS', 'Javascript']); const val2 = new Set(['HTML', 'CSS']); Â Â const result = subSet(val1, val2); Â Â console.log(result); |
true
