JavaScript Facet Filtering

Feb 26, 2018

I'm currently working on adding faceted search to Vegan Realm. I struggled a bit while trying to find an elegant solution in plain JavaScript. I figured that sharing my concept might come in handy for someone trying to achieve a similar result. The complete code of the demo is available here.

RequireJS and its domReady module were used to organize code. No other JavaScript libraries were used. Everything could be refactored into a single file if you're not interested in using modules.

To demo the feature, I created a bunch of fictional books authored by my cats and me. In a real application, these books would be served by an API. The data and its filtering were isolated inside a service module that could be swapped for something else entirely if you need to query an external api.


  "author": {
    "facet_title": "Authors",
    "selected_class": "author_selected"
  "year": {
    "facet_title": "Years",
    "selected_class": "year_selected"

The application assumes that you have knowledge of the possible facet filters available to you in the documents. This knowledge is reflected in FACET_MAPPINGS where you assign a title for your facet (facet_title) and a CSS class for the selected state of your facet (selected_class). This mapping is used for two things:

Adding and removing facets from the UI is done through FACET_MAPPINGS. For example, you could add a new "title" facet to this project just by editing FACET_MAPPINGS.1

The flow of the app

When you load the site, loadResults creates the HTML of the result list. Then, to create the HTML of the facets section, createFacet is called for each of the facets defined in your mapping.

The interesting stuff happens in handleFacetClicks:

Things to consider

All the facet values are shown, whether the result list contains results for a specific value of not. This is because the facet values are built once based on all the results when you load the page. It wouldn't be complex to re-render the facets when the results are filtered though.

The facets are very simple. Selecting an author will unselect other authors for example. A facet will work correctly if there is only one value per field in your documents.

And that's one simple way to create a facet UI in plain JavaScript.

  1. Adding the "title" facet would not make much sense however. ↩︎

Also published on Medium