How To Check If Two Sets Are Equal Using JavaScript

How to check if two Sets are equal using JavaScript

To check if two sets are equal using JavaScript you can use a for loop with has() method. In this article we’ll present the specific steps to do it. Let’s follow along!

Check if two sets are equal using JavaScript 

Use a for loop and has() method

The has() method check if an element with a given value already appears in a set object. If yes, It returns true. Otherwise it return false when the set object has no element with that value.

Syntax:

has(value)

Parameter:

  • value: The value to find in the Set object.

The has() method returns false if an element with the specified value does not exist in the set object; otherwise, it returns true:

var set1 = new Set(['b','a','c']);
var set2 = new Set(['a','c','b']);

// Assuming two set are equals
let equality = true;

if (set1.size === set2.size){
    for (let i of set1)
        if (set2.has(i) == false){
            equality = false;
            break;
        }
}

else equality = false;

if (equality == true)
    console.log("Two sets are equal");
    
else console.log("Two sets are not equal");

Output: 

Two sets are equal

The above example uses the has() method of set type to check if an object value already exists in the set. Additionally, this method runs faster than the includes() method of array.

Reuse code with a function

We can create a function based on the logic of the first approach to make our code more simple and reusable:

function checkEqualSet(set1,set2){

    if (set1.size === set2.size){
        for (let i of set1)
            if (set2.has(i) == false){
                return false;
        }
    }

    else return false;
    return true;
}

Sample test case:

var set1 = new Set(['x','y','z']);
var set2 = new Set(['z','x','y']);

if (checkEqualSet(set1,set2))
    console.log("Two sets are equal");

else console.log("Two sets are not equal");

Output: 

Two sets are equal

Another test case:

var set1 = new Set(['x','x','y']);
var set2 = new Set(['z','x','y']);

if (checkEqualSet(set1,set2))

    console.log("Two sets are equal");
else console.log("Two sets are not equal");

Output: 

Two sets are not equal

If our function checkEqualSet() returns true, it indicates that the two sets provided are equal. Otherwise, it will return false. You have to call the checkEqualSet() function, pass two sets to the parameters, and write your code to handle each boolean situation returned.

Summary

We hope you enjoy our article about how to check if two sets are equal using JavaScript. There are two different methods. It would help if you considered each approach’s pros and cons. If you have any questions or problems, please comment below. Thank you for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *