To check if a Set contains all the items of another Set in TypeScript, you can use the Set.prototype.has
method along with iteration.
In this example,
set1
and set2
containing elements of a specific type.set2
and use the Set.prototype.has
method to check if it exists in set1
.set2
is not found in set1
, we set containsAllItems
to false
, otherwise true
.// Define Sets with items
const set1: Set<string> = new Set(["apple", "banana", "orange", "grape", "melon"]);
const set2: Set<string> = new Set(["banana", "orange"]);
// Check if set1 contains all items of set2
let containsAllItems: boolean = true;
set2.forEach(item => {
if (!set1.has(item)) {
containsAllItems = false;
}
});
// Print result
console.log(`Does set1 contain all items of set2? ${containsAllItems}`);
Does set1 contain all items of set2? true
In this example,
set1
and set2
containing elements of a specific type.set2
and use the Set.prototype.has
method to check if it exists in set1
.set2
is not found in set1
, we set containsAllItems
to false
.// Define Sets with items
const set1: Set<string> = new Set(["apple", "banana", "orange", "grape", "melon"]);
const set2: Set<string> = new Set(["banana", "peach"]);
// Check if set1 contains all items of set2
let containsAllItems: boolean = true;
set2.forEach(item => {
if (!set1.has(item)) {
containsAllItems = false;
}
});
// Print result
console.log(`Does set1 contain all items of set2? ${containsAllItems}`);
Does set1 contain all items of set2? false
In this tutorial, we learned How to check if a Set contains all the items of Another Set in TypeScript language with well detailed examples.