The set in TypeScript is a novel data structure introduced in the ES6 edition of JavaScript. It enables the storage of unique data (ensuring that each value appears only once) within a List, akin to other programming languages. While sets share some similarities with maps, they are designed to hold only keys and do not include key-value pairs.
Create Set
We can create a set as below.
let mySet = new Set();
Set methods
The TypeScript set methods are listed below.
| SN | Methods | Descriptions |
|---|---|---|
1. |
set.add(value) | It is used to add values in the set. |
2. |
set.has(value) | It returns true if the value is present in the set. Otherwise, it returns false. |
3. |
set.delete() | It is used to remove the entries from the set. |
4. |
set.size() | It is used to returns the size of the set. |
5. |
set.clear() | It removes everything from the set. |
Example
The following example helps illustrate the various set methods.
let studentEntries = new Set();
//Add Values
studentEntries.add("John");
studentEntries.add("Peter");
studentEntries.add("Gayle");
studentEntries.add("Kohli");
studentEntries.add("Dhawan");
//Returns Set data
console.log(studentEntries);
//Check value is present or not
console.log(studentEntries.has("Kohli"));
console.log(studentEntries.has(10));
//It returns size of Set
console.log(studentEntries.size);
//Delete a value from set
console.log(studentEntries.delete("Dhawan"));
//Clear whole Set
studentEntries.clear();
//Returns Set data after clear method.
console.log(studentEntries);
Output:
Upon executing the aforementioned code snippet, the resulting output is as follows.
Chaining of Set Method
The set method in TypeScript also facilitates the chaining of the add method. This can be illustrated through the following example.
Example
let studentEntries = new Set();
//Chaining of add() method is allowed in TypeScript
studentEntries.add("John").add("Peter").add("Gayle").add("Kohli");
//Returns Set data
console.log("The List of Set values:");
console.log(studentEntries);
Output:
Iterating Set Data
We can traverse the values or entries of a set utilizing the 'for...of' loop. The subsequent example illustrates this concept more effectively.
Example
let diceEntries = new Set();
diceEntries.add(1).add(2).add(3).add(4).add(5).add(6);
//Iterate over set entries
console.log("Dice Entries are:");
for (let diceNumber of diceEntries) {
console.log(diceNumber);
}
// Iterate set entries with forEach
console.log("Dice Entries with forEach are:");
diceEntries.forEach(function(value) {
console.log(value);
});
Output: