Table of contents
1.
Introduction
2.
Set Syntax
3.
Set Methods
3.1.
set.add(value) 
3.2.
set.has(value)
3.3.
set.delete()
3.4.
set.clear()
3.5.
set.size() 
4.
Set Iterations
4.1.
set.entries()
4.2.
set.values()
4.3.
set.keys()
4.4.
set.forEach(callbackFunction[, thisArgument])
4.5.
for-Of Set
5.
Set Operations
5.1.
Union
5.2.
Difference
5.3.
Intersection
5.4.
Mapping
5.5.
Filtering
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Typescript Set

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

To store unique elements, Es6 introduced the Set class. Javascript supports data structures like Set, Map, and WeakMap with Es6.

Objects that store values are called set objects. As you iterate through the elements of a set, you can arrange them in insertion order. Values can only appear once in a set. Setting unique values of any type is possible with the Set object, whether primitive values or object references. 

Set is not a built-in class in Typescript, but it supports the same data structure added to ES6. The set functionality is similar to maps, but it stores only keys, not key-value pairs.

Set Syntax

Set objects use the let and new keywords to declare themselves.

A new Set object is created with the Set() constructor.

let newSet = new Set();  

Or

Use data type to create a set

let newSet = new Set<Integer>();

Or

Assigning the values while creating the set

let setData=new Set(['value1', 'value2', 'value3']); 

Set Methods

set.add(value) 

The function adds values to the end of the set.

let newSet = new Set();    //creating a set 

newSet.add('Ninja_1');     //Adding elements to the set
newSet.add('Ninja_2');
newSet.add('Ninja_3');
newSet.add('Ninja_4');

console.log("New Set is:");
console.log(newSet);

 

Output:

"New Set is:" 
Set (4) {"Ninja_1", "Ninja_2", "Ninja_3", "Ninja_4"}

 

Set() and add() methods can also be chained in TypeScript. Consider:

let newSet = new Set();    //creating a set
newSet.add("Ninja_1").add("Ninja_2").add("Ninja_3").add("Ninja_4");    //Add elements to          the set
console.log(newSet);

set.has(value)

The value is checked against the set to see if it exists. If not, it returns false.

let newSet = new Set();    //creating a set

newSet.add('Ninja_1');     //Add elements to the set
newSet.add('Ninja_2');
newSet.add('Ninja_3');
newSet.add('Ninja_4');


//Check whether the element Ninja_2 and Ninja_5 is present in the set or not
console.log(newSet.has('Ninja_2'));
console.log(newSet.has('Ninja_5'));

 

Output:

true 
false 

set.delete()

The function removes the elements from the set.

let newSet = new Set();    //creating a set

newSet.add('Ninja_1');     //Add elements to the set
newSet.add('Ninja_2');
newSet.add('Ninja_3');
newSet.add('Ninja_4');

console.log("Before deleting elements in the Set", newSet);

newSet.delete('Ninja_1');    //deleting elements from the set 
newSet.delete('Ninja_3');

console.log("After deleting elements in the Set", newSet);

 

Output:

"Before deleting elements in the Set",  Set (4) {"Ninja_1", "Ninja_2", "Ninja_3", "Ninja_4"} "After deleting elements in the Set",  Set (2) {"Ninja_2", "Ninja_4"} 

set.clear()

The functions removes every value from the set.

let newSet = new Set();    //creating a set

newSet.add('Ninja_1');     //Add elements to the set
newSet.add('Ninja_2');
newSet.add('Ninja_3');
newSet.add('Ninja_4');

console.log("Before clearing the Set",newSet);

newSet.clear()     // clearing elements from the set

console.log("After clearing the Set",newSet);

 

Output:

"Before clearing the Set",  Set (4) {"Ninja_1", "Ninja_2", "Ninja_3", "Ninja_4"}  
"After clearing the Set",  Set (0) {} 

set.size() 

This function return the size of the set.

let newSet = new Set();   //creating a set

newSet.add('Ninja_1');    //Add elements to the set
newSet.add('Ninja_2');
newSet.add('Ninja_3');
newSet.add('Ninja_4');

console.log("Size of the set: ",newSet.size);    // returns the size of the set

 

Output:

"Size of the set: ",  4

Set Iterations

set.entries()

The iterator object is returned in the order of insertion. It contains an array of [value, value] for each element in the Set object.

let newSet = new Set(); //creating a set

newSet.add("Ninja_1").add("Ninja_2").add("Ninja_3").add("Ninja_4"); //Add elements to the set

for (let [key,values] of newSet.entries()) console.log(key,values).entries()) console.log(values)

set.values()

This function returns a new iterator object that contains information about each element in the Set object in the insertion order.

let newSet = new Set(); //creating a set

newSet.add("Ninja_1").add("Ninja_2").add("Ninja_3").add("Ninja_4"); //Add elements to the set

for (let values of newSet.values()) console.log(values)

set.keys()

The Set object is iterated using this method. Each element from Set is returned in insertion order.

let newSet = new Set(); //creating a set

newSet.add("Ninja_1").add("Ninja_2").add("Ninja_3").add("Ninja_4"); //Add elements to the set

for (let values of newSet.keys()) console.log(values)

set.forEach(callbackFunction[, thisArgument])

Every value in the Set object is called once by callbackFn, in insertion order. If the thisArgument parameter is specified, it will be used as this value in all calls to callbackFunctions.

let newSet = new Set(); //creating a set

newSet.add("Ninja_1").add("Ninja_2").add("Ninja_3").add("Ninja_4"); //Add elements to the set

newSet.forEach(function(value) {
  console.log(value)
})

for-Of Set

Using Of in for loop can be used in an iteration of Set Objects.

let newSet = new Set(); //creating a set

newSet.add("Ninja_1").add("Ninja_2").add("Ninja_3").add("Ninja_4"); //Add elements to the set

for (let values of newSet) {  
    console.log(values);   
} 

Set Operations

Union

Combine elements from both sets1 and 2.

let set1 = new Set([3,8,9]);
let set2 = new Set([8,3,2]);

const union = new Set([...set1,...set2]);

console.log(union)
// returns Set (4) {3, 8, 9, 2} 

Difference

Make a set that contains only the elements of set1 that do not appear in set2. Minus (-) is another name for this operation.

let set1 = new Set([3,8,9]);
let set2 = new Set([8,3,2]);

const difference = new Set(
  Array.from(set1).filter(x => !set2.has(x))
);

console.log(difference)
// returns Set (1) {9} 

Intersection

Make a new set out of the elements of set1 that appear in set2 as well.

let set1 = new Set([3,8,9]);
let set2 = new Set([8,3,2]);

let intersection = new Set(
  Array.from(set1).filter(x => set2.has(x))
);

console.log(intersection)
// Set (2) {3, 8} 

Mapping

There is no .map() method for sets. Instead, we can use the one Arrays have. By calling a specific function on each element in the parent array, the map() method in JavaScript creates an array. This method does not modify the parent array. 

let set1 = new Set([3,8,9]);
let set2 = new Set([8,3,2]);

const mapping = new Set(
  Array.from(set1).map(x => x * 2)
);

console.log(mapping)
// returns Set (3) {6, 16, 18} 

Filtering

Sets can't be filtered directly by .filter(), so the Array method is needed. The filter() method creates a new array containing the elements that pass the specified test.  

let set1 = new Set([3,8,9]);
let set2 = new Set([8,3,2]);

let filtered = new Set(
  Array.from(set1).filter(x => (x % 2) === 0)
);

console.log(filtered)
// returns Set (1) {8} 

Frequently Asked Questions

  1. Does the set represent an array?
    The most significant difference between an Array and a Set is that an Array can contain duplicate values while a Set cannot. One major difference between arrays and sets is that data in an array is ordered by index. In contrast, sets use keys & the elements are iterated in the order of insertion.
     
  2. How does the new set work?
    ES6 (ES2015) introduces sets as a new object type that allows creating collections of unique values. Arrays and object literals can both contain values that are primitives, such as strings or integers, or more complex objects, such as arrays and object literals.
     
  3. Why are sets faster than arrays?
    Tests for membership in an array are slower than testing whether a set contains an object. Because it is a static collection type, it will not be possible to add or remove objects after initialization. This may be an essential factor to consider when choosing an Array.
     
  4. How come Sets have a .size parameter, but Arrays have a .length parameter? 
    For indexable collections like Arrays and Strings, the length property is .length, while unindexed collections like Maps and Sets are .size:
    → Integers are used to determine .length; the highest index plus one is used.
    → The .size counts how many elements are in a collection.

Conclusion

A data structure known as a set has been added to ES6 JavaScript that helps store data of distinct values that occurs only once into a list available in different programming languages like C#, Java, etc. In this article, different aspects such as syntax, methods, and examples of set in typescript are explained in detail.

Become more familiar with other areas of web development if you're new to it by learning from coding ninja’s guided path, which offers all the courses free of cost.

Live masterclass