TypeScript Set

Set is a new data structure introduced in ES6, similar to Map. A typescript Set allows us to store distinct values in a List similar to other programming languages e.g. Java, C#.

1. Creating Set

Use Set type and new keyword to create a Set in typescript.

let directions = new Set<string>();

To create a Set with initial values we can pass the values in an array.

let directions = new Set<string>(['east', 'west']);

2. Add, Retrieve and Delete Values from Set

  1. set.add(v) – adds values into the Set.
  2. set.has(v) – checks the existence of a value in the Set.
  3. set.delete(v) – deletes a value from the Set.
  4. set.clear() – clear all values from the Set.
  5. set.size – ‘size‘ property will return size of Set.
//Create a Set
let diceEntries = new Set<number>();
 
//Add values
diceEntries.add(1);
diceEntries.add(2);
diceEntries.add(3);
diceEntries.add(4).add(5).add(6);   //Chaining of add() method is allowed
 
//Check value is present or not
diceEntries.has(1);                 //true
diceEntries.has(10);                //false
 
//Size of Set 
diceEntries.size;                   //6
 
//Delete a value from set
diceEntries.delete(6);              // true
 
//Clear whole Set
diceEntries.clear();                //Clear all entries

3. Iterating over a Set

Use for loop to iterate over the values in a Set.

let diceEntries = new Set<number>();
 
//Added 6 entries into the set
diceEntries.add(1).add(2).add(3).add(4).add(5).add(6);
 
//Iterate over set entries
for (let currentNumber of diceEntries) {
    console.log(currentNumber);     //Prints 1 2 3 4 5 6
}
 
// Iterate set entries with forEach
diceEntries.forEach(function(value) {
  console.log(value);               //Prints 1 2 3 4 5 6
});

Drop me your questions in the comments section.

Happy Learning !!

Leave a Reply

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.