How to filter a set - JavaScript

Mo Ibra

Mo Ibra

Dec 22, 2022

In this article we will learn how to filter a set.

It is very common to filter a set in JavaScript.


Problem

Now we have a problem, which is that we want to filter the set.

Imagine that we have a set with a set of numbers like this:

// set
new Set([1, 2, 3, 4, 200, 300, 400]);

// Set(7) { 1, 2, 3, 4, 200, 300, 400 }

And we want to delete the numbers above 100 to make it like this.

new Set([1, 2, 3, 4]);

// Set(4) { 1, 2, 3, 4 }

How to solve this problem

Well, to solve this problem there is more than one solution:

  • Using forEach.
  • Using filter

Filter a set using forEach

We can use forEach to filter our set.

// 1. Define a set
const set = new Set([1, 2, 3, 4, 200, 300, 400]);

// 2. Iterate over set
set.forEach((value, key) => {

    // 3. If value > 100
    if (value > 100) {
        // 4. Delete element
        set.delete(key);

        console.log(`Deleted ${value}`);
    }
});

// 5. Print result:
console.log(set);

Output

Deleted 200
Deleted 300
Deleted 400
Set(4) { 1, 2, 3, 4 }

We used the forEach method to iterate over the Set object.


Filter a set using filter method

We can use filter to filter our set as well.

Example

// 1. Define a set
const set = new Set([1, 2, 3, 4, 200, 300, 400]);

// 2. Create new set
const filter = new Set(

    // 3. Filter our set
    Array.from(set).filter((value) => {

        // 4. If value more than 100
        if (value > 100) {

            // Don't add it to new set
            return false
        }

        // Otherwise add it to new set
        return true;
    })
)

// Result:
console.log(filter);

Output

Set(4) { 1, 2, 3, 4 }

How it works?

  • First, we defined our set const set
  • Second, we defined a new set const filter
  • Third, we filter our set using filter method
  • Then, we check if value is more than 100 or not
// 4. If value more than 100
if (value > 100) {

    // Don't add it to new set
    return false
}

// Otherwise add it to new set
return true;
  • If value more than 100, don't add it into new set
  • Otherwise add it.

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: