An Introduction to Sets in JavaScript

What is a Javascript Set?

In Mathematics, a set is a collection of distinct elements. The elements may be similar or dissimilar types.

Javascript brings this concept of a mathmatical set through the Set object.

  • A Javascript Set is a collection of unique elements — any element in a Set can occur only once.
  • The content of a Set can vary from simple data types such as numbers and strings to complex types such as arrays and objects.
  • The insertion order of elements is preserved in a Set.

Defining a Set

  • Defining an empty Set

    A Set can be defined by creating a new Set object. Passing no parameters will create an empty set.

    var set_ob = new Set();
  • Defining a Set with initial elements

    To create a Set with initial elements, an iterable object can be passed as the parameter. In simple terms, iterable objects are those objects that can be looped with a for..of statement. Arrays and strings (which is an array of characters) are built-in iterable objects. Normal Javascript objects are not iterable, so they cannot be passed as parameter.

    The created Set object will be populated with the values of the passed iterable object.

    Creating a Set object from an array :

    var set_ob = new Set([1, 2, 'a', 4, 'b']);
    
    // contains 5 elements : [1, 2, 'a', 4, 'b']
    console.log(set_ob);
    

    When a Set is created from a string, the characters of the string becomes the elements of the Set :

    var set_ob = new Set("TREE");
    
    // contains 3 elements : ["T", "R", "E"]
    // duplicate "E" is not included
    console.log(set_ob);
    

Adding New Element to Set

To add a new element to a Set, the add method is called. The value to be added is passed as the parameter.

var set_ob = new Set();

// adding simple datatype
set_ob.add('A');

// adding an object
set_ob.add({ key: "T35", value: "Architecture" });

// contains 2 elements : ["A", {key:"T35", value:"Architecture"}]
console.log(set_ob);

The return value of the add method is the Set object itself. This is helpful in chaining. For example, the above 2 separate additions could be combined in a single line :

set_ob.add('A').add({ key: "T35", value: "Architecture" });

Removing an Element from Set

To remove an element from any given Set, the delete method is called. The value to be removed is passed as parameter to the method.

var set_ob = new Set([1, 2, 3, 4]);

// Remove value 4
set_ob.delete(4);

The return value is a boolean true if element was removed successfully, and false otherwise.

Removing all Elements from Set

To remove all elements from a Set, the clear method is called.

var set_ob = new Set([1, 2, 3, 4]);

// removes all elements
set_ob.clear();

Getting Size of Set

To get the number of elements in the Set, the size property is called.

var set_ob = new Set(['a', 'b', 1, 2]);

// 4
console.log(set_ob.size);

Checking If Element Present in Set

To check whether a particular element exists within a Set, the has method is called. The element to look for is passed as the parameter. The method returns a boolean true if element exists within the Set, and false if not found.

var set_ob = new Set([1, 2, 3, 4]);

// true
console.log(set_ob.has(4));

// false
console.log(set_ob.has(5));

Getting All Elements in a Set

The values method can be used to get all values in a Set. It returns an iterable object which can be looped with for..of statement.

var set_ob = new Set([1, 2, 3, 4]);

for(var element of set_ob.values()) {
	console.log(element);
}

// output
// 1
// 2
// 3
// 4

Looping Through a Set

The simplest method of looping over a Set is by using a for..of statement. The elements are looped in the order they were inserted.

var set_ob = new Set([1, 2, [3,4], {a: 546}, "Hello"]);

for(var element of set_ob) {
	console.log(element);
}

// output
// 1
// 2
// [3,4]
// { a: 546 }
// "Hello"

When to Use Set ?

Sets have some advantages over the Array datatype which may be useful in some cases :

  • One can prefer to use Set over the traditional Array when trying to avoid duplicate values.
  • Removing element in a Set is easier than doing so in an Array. This is because to remove an element in an Array, first the index of the element has to be found and then the element can be deleted using the index. Whereas in Set one has to simply call the delete method.
  • Again, Set is better suited for mathematical set operations such as union, intersection and difference.

You can choose an appropriate datatype depending on your use-case.

More Information

Sets have more methods but for the sake of simplicity they are not discussed in this tutorial. These are the resources from which you can get more information :

Loading Comments