Set object is a new built-in data type added in Javascript. A Set object is special in the sense that it stores only unique values and values present in it can be of different types (numbers, objects, array etc).
What is a Javascript Set Object ?
In Mathematics, a set is a collection of distinct elements. The elements may be similar or dissimilar types.
Javascript brings this concept of a mathematical set through the Set object.
- A Javascript Set object is a collection of unique elements — any element in a Set can occur only once. Duplicates are automatically removed from a Set.
- 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. For example, the first element that was added to a Set will always stay at the first regardless of other elements being added to the Set.
Creating a Set Object
-
Creating an empty Set Object
A Set object can be defined by creating a new Set object. Passing no parameters will create an empty set.
var set_ob = new Set();
-
Creating a Set Object with initial elements
To create a Set object 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 the Set Object
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 the 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 the 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 the 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 the Set Object
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 the Set
The values() method can be used to get all values in a Set object. 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 object 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 the Set Data Type ?
Sets have some advantages over the Array data type 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 object is better suited for mathematical set operations such as union, intersection and difference.
You can choose an appropriate data type 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 :