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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

4 thoughts on “TypeScript Set”

  1. While I do appreciate the help for function names (nice job!), I think it would nice to have something that illustrates the idea that sets only allow distinct values in the example. Perhaps add another 1 to the set and then call size should suffice.

    Thanks!

    Reply
    • Hi Mike, Thanks for the feedback. Set allows distinct values.. is written in post introduction. I am assuming that people who reach this article will already know what exactly a set is (theoretically). This post is to help those who are looking for exact function names (as you pointed out) in typescript.

      Reply
  2. There is an error in your documentation. List item 1 should read set.add() – method to add values in the Set

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.