In TypeScript, you can check if two sets are equal by comparing their size and elements using loops or the spread operator.
In this example,
set1
and set2
.setsAreEqual
to compare the sets.set1
using the forEach
method and check if each element is present in set2
.true
; otherwise, we return false
.let set1: Set<number> = new Set([1, 2, 3]);
let set2: Set<number> = new Set([1, 2, 3]);
function setsAreEqual(set1: Set<any>, set2: Set<any>): boolean {
if (set1.size !== set2.size) return false;
let isEqual = true;
set1.forEach(item => {
if (!set2.has(item)) {
isEqual = false;
}
});
return isEqual;
}
console.log(setsAreEqual(set1, set2)); // Output: true
true
In this example,
set1
and set2
.[...]
) to convert sets to arrays and then compare the arrays for equality.let set1: Set<number> = new Set([1, 2, 3]);
let set2: Set<number> = new Set([4, 5, 6]);
function setsAreEqual(set1: Set<any>, set2: Set<any>): boolean {
return JSON.stringify([...set1]) === JSON.stringify([...set2]);
}
console.log(setsAreEqual(set1, set2)); // Output: false
false
In this tutorial, we learned How to check if Two Sets are Equal in TypeScript language with well detailed examples.