Sets
Explore how sets work in JavaScript with this lesson covering set representation, adding and removing items, membership tests, and set operations like union and intersection. Learn through interactive exercises and get solutions to build your understanding of this data structure.
Introduction
A set is an unordered collection of related members in which no member occurs more than once. A set that doesnt contain any element is often called null set. Below is a typical representation of set:
The most common set operations are given below:
Union - This is wherein a new set is constructed by combining the members of one set with the members of another set.
Intersection - This is wherein a new set is constructed by adding all the members of one set that also exist in a second set.
Difference - This is wherein a new set is constructed by adding all the members of one set except those that also exist in a second set.
Let's now look at how we can manage and work with sets using JavaScript.
Set Representation in JavaScript
The code below is the most typical representation of a set in JavaScript:
The set is represented as an Object and the values of the set can be inserted as properties. The size is maintained separately using a size variable. There are other ways of implementing sets in JavaScript. We have picked Object for its simplicity.
Now let's look at how we can add elements into our set. The snippet of the code below showcases how we can add values to our set data structure:
The first check is done to see if the data actually exists in our set. This is done by using the hasOwnProperty method which is available for JavaScript objects. If not, then the data value is added to the set by setting the property of the object to the data which is passed to the add function. The associated value is set to true, just to indicate that the property is part of the set. Technically in this implementation of a set, the value can be set to anything.