This post will discuss how to filter a set in JavaScript.

Filtering a set means creating a new set with elements of the original set, but containing only the elements that satisfy a certain condition. Some of the methods we can use to filter a set in JavaScript are:

1. Using Set.forEach() function

A simple solution is to iterate over each element of the set using forEach(), and delete the element from the set if it does not meet the condition using the delete() function. The forEach() function takes a callback function as an argument, which is executed for each element of the set. The delete() function takes a value as an argument, and removes it from the set if it exists. This modifies the original set in-place. For instance:

Download  Run Code

 
We can also use a for…of loop to iterate over the values of a set and delete the ones that we don’t want from the original set using the Set.delete() function. This function also modifies the original set in-place.

Download  Run Code

2. Using Array.filter() function

Another alternative is to use the Array.filter() function, which takes a callback function as an argument and returns a new array with elements passing the implemented condition. We can use this function to create a new array with the required elements from the original set, and then pass the filtered array to the Set() constructor. This will work, but requires conversion between the set and the array. For instance:

Download  Run Code

3. Using Lodash or Underscore.js

A more convenient way to filter a set in JavaScript is using a third-party library. To filter a set using Lodash or Underscore.js, we can use their filter() function. This function iterates over elements of a collection and returns an array of all elements that pass a predicate function. We can then convert the filtered array back into a set using the Set() constructor. For instance:

Download  Run Code

That’s all about filtering a set in JavaScript.