![]() |
A Set in TypeScript is a bunch of unique values. It is part of the ECMAScript 2015 (ES6) standard and is implemented as a native object in JavaScript. Unlike arrays, sets do not allow duplicate elements, making them useful for storing collections of unique items. TypeScript provides strong typing for sets, ensuring type safety and autocompletion in the development environment. Table of Content Creating a New SetYou can create a new set by using the Set constructor. Syntaxlet mySet = new Set<Type>(); Example: Creating new set using the numbers
OutputSet { 1, 2, 3 } Adding Elements to a SetElements can be added to a set using the add method. SyntaxmySet.add(value); Example: Adding new fruits to the set.
OutputSet { 'apple', 'banana', 'orange' } Checking if an Element Exists in a SetIt has method checks if an element exists in the set. SyntaxmySet.has(value); Example: Checking if the element exist or not.
Outputtrue
false Removing Elements from a SetElements can be removed from a set using the delete method. SyntaxmySet.delete(value); Example: Removing an element from the set.
OutputSet { 'red', 'blue' } Iterating Over a SetYou can iterate over a set using for…of or forEach. Syntaxfor (let item of mySet) {
console.log(item);
}
mySet.forEach((item) => {
console.log(item);
}); Example: Iterating over set and printing each element.
Output 1
2
3
4
5
1
2
3
4
5 Converting a Set to an ArrayA set can be converted to an array using the spread operator or the Array.from method. Syntaxlet myArray = [...mySet];
let myArray2 = Array.from(mySet); Example: In this example we are converting a set to array.
Output[1, 2, 3]
[1, 2, 3] Performing Set OperationsSets can be used to perform mathematical operations like union, intersection, and difference. Syntaxlet union = new Set([...set1, ...set2]);
let intersection = new Set([...set1].filter(x => set2.has(x)));
let difference = new Set([...set1].filter(x => !set2.has(x))); Example: Performing set operation union, intersection and difference.
OutputSet { 1, 2, 3, 4, 5, 6 }
Set { 3, 4 }
Set { 1, 2 } Benefits of Using Set
|
Reffered: https://www.geeksforgeeks.org
TypeScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |