How to Create a Set in TypeScript

In TypeScript, the Set is a new data structure introduced in ES6 that stores a group/collection of unique values.  The key feature of a set is that it does not allow duplicate values, but it stores only keys, not key-value pairs. In this article, we will explore How to Create a Set in TypeScript.

Create a Set in TypeScript

Create a TypeScript Set

To Create a Set in TypeScript, simply use the “Set” constructor.

let gender = new Set<string>();

gender = new Set<string>(['Male', 'Female']);

console.log(gender);

Output :

Set(2) { 'Male', 'Female' }

Set Methods

MethodsDescription
Set.add(value)Add the specified value to the Set.
set.has(value)Checks the existence of the specified value in the Set, if it is the value present in the function it returns true or else it returns false.
set.delete(value)Deletes the specified value from the Set.
set.clear()Clears all the values from the Set.
set.sizeChecks the existence of the specified value in the Set, if it is value present in the function it returns true or else it returns false.
set.values()Returns an iterator with the values of the set
set.keys()Returns an iterator with the values of the ‘Set’. Returns the same result as the values() function.
set.entries()Return an iterator object with value/value pairs.
Set.forEach()Invokes a callback on each value pair.

Set Method Examples

How to Add an Element to a ‘Set’?

You can add elements to a Set using the provided add function.

// Create a Set
let setEntries = new Set<number>();

// To Add values
setEntries.add(100);
setEntries.add(101);
setEntries.add(102);
setEntries.add(103).add(104).add(105).add(106).add(107);

How to check if a Set contains a key?

Check the existence of the specified value in the Set, using the provided function ‘has’

// check value is present or not

setEntries.has(103);
setEntries.has(110);

Get the Size of the Set?

// Get Set Size

setEntries.size;

Delete a value from Set?

// Remove a value from Set

setEntries.delete(102);

How to Remove all entries in Set?

// Clear all Set Values
setEntries.clear();

How to iterate over a Set?

We can iterate over a Set using the for-of and forEach loops.

Using for-of

let Setvalues = new Set<number>();

// Add value to Set
Setvalues.add(201);
Setvalues.add(202).add(203).add(204).add(205);
// or

const Setvalues1 = new Set([500,501,502,503,504]);

//iterate Set with for-of
for (let val of Setvalues){
    console.log(val);
}

Using forEach

// iterate entries with forEach
Setvalues.forEach(function(val){
 console.log(val);
});

//alternatively yo can use the built -in Javascript forEach function

Setvalues.forEach(val=>console.log(val));

More article – How to Create a TypeScript Map

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments