DEV Community

Cover image for Filtering Many Options on the Frontend
Karl L. Hughes
Karl L. Hughes

Posted on

Filtering Many Options on the Frontend

A friend of mine recently emailed me asking how he might filter a large list of items in Javascript. He started out with just a couple filters, but as more got added, it became increasingly complex to filter out matches.

I ran across a similar problem recently when building a new filtering feature for CFP Land. I wanted users to be able to limit conferences with open CFPs to those that matched their criteria, and since the list isn't that big (usually fewer than 100), I decided to implement it on the frontend.

While this solution isn't optimized, it does limit the complexity of any one filter. In cases where performance differences are negligible it's better to favor solutions that make code more readable to those that are optimal.

First, I created a master filter function:

function filter(allResults, options) {
    return allResults.filter(result => passesFilter(result, options))
}
Enter fullscreen mode Exit fullscreen mode

Where allResults is the array of all items in the list (conferences in my case).

Next, I created a passesFilter function that will ultimately return a boolean (true or false) depending on whether an individual item passes all the filter options given:

function passesFilter(result, options) {
    const results = [];

    if (option.firstOption) {
        results.push(resultPassesFirstOption(result, options.firstOption));
    }

    // TODO: Repeat for as many options as you want.
    // You'll end up with an array of true/false statements

    return results.every(result => result);
}
Enter fullscreen mode Exit fullscreen mode

The last line uses every to return true if all elements in the results array are true.

Finally, I implemented my resultPassesFirstOption function where the real business logic lies:

function resultPassesFirstOption(result, option) {
    // TODO: Return true or false depending on the result and option
}
Enter fullscreen mode Exit fullscreen mode

Now, you just need to create functions and if statements to process each option that you want to support.

What do you think? Do you know a more efficient way to filter items using complex options in Javascript? Let me hear your solutions to the problem in the comments 👇.

Top comments (1)

Collapse
 
rajajaganathan profile image
Raja Jaganathan

Nice read!. Try specification patterns en.m.wikipedia.org/wiki/Specificat...