Sets

This lesson will look at how to work with Sets in JavaScript. We will see how we can create Sets, access elements of a Set, and various other functionalities on Sets.

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:

{12345}

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:

Press + to interact
function Set() {
this.set = {};
this.size = 0;
}

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.

...