TypeScript set is a new data structure added in ES6 version of JavaScript. It allows us to store distinct data (each value occur only once) into the List similar to other programming languages. Sets are a bit similar to maps, but it stores only keys, not the key-value pairs.
We can create a set as below.
let mySet = new Set();
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. |
We can understand the set methods from the following example.
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);
When we execute the above code snippet, it returns the following output.
TypeScript set method also allows the chaining of add() method. We can understand it from the below 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);
We can iterate over set values or entries by using 'for...of' loop. The following example helps to understand it more clearly.
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); });