JavaScript Program to Illustrate Different Set Operations
You can keep track of distinct values of any type in JavaScript with the help of the built-in Set object. Sets are versatile objects that can be used for things like data processing and analysis thanks to their ability to undergo a number of operations on themselves, such as union, intersection, and difference. A JavaScript program that demonstrates several set operations is discussed here.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Set Union Operation
Union Set is a set made by combining the elements of two sets. A new set unionSet
is created using new Set()
.
The unionSet variable contains all the values of setA initially stored in it. Then, the for...of
loop is used to iterate through all the elements of setB and add them to unionSet using the add()
method one after the other.
The set does not contain duplicate values in it. Hence, if the set while merging contains the same values, the latter value is discarded.
// perform function to perform union operation
// contain elements of both sets
function union(a, b) {
let unionSet = new Set(a);
for (let i of b)
unionSet.add(i);
return unionSet
}
// two sets of fruits
const setA = new Set(['orange', 'mango', 'apple', 'litchi']);
const setB = new Set(['grapes', 'apple', 'banana']);
const result = union(setA, setB);
console.log(result);
Set { "apple", "mango", "orange", "grapes", "banana" , "litchi" }
Set Intersection Operation
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 traversed in setA and is present in setB, they are added to the intersection set and is finally returned.
// function to perform intersection operation
// elements of set a that are also in set b
function intersection(setA, setB) {
let intersectionSet = new Set();
for (let i of setB) {
if (setA.has(i))
intersectionSet.add(i);
}
return intersectionSet;
}
// two sets of fruits
const setA = new Set(['apple', 'mango', 'orange', 'litchi', 'strawberry']);
const setB = new Set(['grapes', 'apple', 'banana']);
const result = intersection(setA, setB);
console.log(result);
Set { "apple" }
Conclusion
As a result, sets are a crucial data structure in JavaScript that let us store and work with groups of distinctive values. We have a number of built-in methods for performing set operations, including union, intersection, difference, and symmetric difference, provided by the Set object.
In our JavaScript programs, we can easily manipulate and combine sets using these methods, which will result in more efficient and succinct code. We can perform complex operations with little code and lessen the possibility of bugs and errors by utilizing the power of sets.