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
set.add(v)
– adds values into theSet
.set.has(v)
– checks the existence of a value in theSet
.set.delete(v)
– deletes a value from theSet
.set.clear()
– clear all values from theSet
.set.size
– ‘size
‘ property will return size ofSet
.
//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 !!