This week I was trying to track down a weird production error and I was having a bit of a problem. All our issues are logged to a database but the interface, while it has had a few facelifts over the years, it is still outdated by modern standards. It is possible to select criteria to filter errors by specific columns but I thought it would be cool to have something a little more granular.

I love any good opportunity to use Vue, so I thought I would create a filter that would allow me to "drill down" the data in our error reports. The drill down filter works by providing the user with a search input box that will allow them to free form search terms; each term separated by a pipe character and each term will further refine the results. Since I cannot really share our error reporting tool, I thought I would throw together a quick demo.

The code is pretty simple:

new Vue({
  el: '#app',
  data() {
    return {
      users: [],
      searchText: ""
    }
  },
  computed: {
    filteredUsers: function () {
      let filtered = this.users;
      if(this.searchText.length){
        let terms = this.searchText.split('|');
        for(let i = 0; i < terms.length; i++){
          if(!terms[i].length) continue;
          filtered = filtered.filter(user => {
          return (
            user.name.toLowerCase().includes(terms[i].toLowerCase()) ||
            user.username.toLowerCase().includes(terms[i].toLowerCase()) ||
            user.email.toLowerCase().includes(terms[i].toLowerCase()) ||
            user.website.toLowerCase().includes(terms[i].toLowerCase())
          );
        });        
        }
      }
      return filtered;
    }
  },
  created: function() {
    fetch('https://jsonplaceholder.typicode.com/users')
     .then(res => res.json())
     .then(json => {
      this.users = json; 
     });
  }
})

When the Vue instance is created I am using fetch to load some placeholder data and save it to this.users. The computed property filteredUsers is where all the real work is done. Every time searchText is updated (this is bound to the text input on the page) I break the string into the individual filter terms and then apply each filter in order.

I am using a very basic data set with 10 data points so the actual usefulness might not be that apparent. Where it really shines is when you have hundreds (or thousands) of data points. Each additional search term will further reduce the results of the previous term.

Multi-Filter Demo`

Enjoy!