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.