DEV Community

Cover image for How to Filter Complex Javascript Arrays
Angus Allman
Angus Allman

Posted on • Originally published at

How to Filter Complex Javascript Arrays

TL;DR I've revived an open-source npm package that I initially built a couple of years ago but have given some TLC in the last few days. You can find it here:

A few years ago, a colleague and I were faced with a problem. We had to make a dashboard with dynamic, intelligent filters for multiple types of data from objects to strings. Usually this would have been a relatively simple thing to accomplish with Javascript's filter() function but in this instance we had no real way of knowing what the user was going to try and filter on since the data could vary so much. To help solve the problem, I built a small, single JS file which allowed us to construct logic like Laravel's Eloquent queries. It meant that we could turn a long, meandering condition inside the filtering function to look more like English. Ultimately, we loved working with it and I released it as a small npm package.

Let's take a look at an example and see how it makes life simpler for developers who find themselves with a whole load of data and no easy way to filter it:

// without or-where
users.filter(user => {
    return ( == 'Angus' || == 'Jess' || == 'Aaron') && user.age >= 25;

//with or-where
filter = new Builder(users);
filter.whereIn('name', ['Angus', 'Jess', 'Aaron'])
      .where('age', '>=', 25)
Enter fullscreen mode Exit fullscreen mode

Even in this relatively basic example it's easy to see the benefits of it. Rather than needing to read the logic gates and pay attention to the brackets, you can read the query like it's English.

Using the built in methods (where(), orWhere(),... etc) you build up a query which is eventually passed to Javascript's filter() method when you call get(). That's all there is to it! You can create incredibly flexible queries with a few simple building blocks leaving your code readable and efficient. What's not to love?

You can find the full documentation on github: Feel free to contribute or open an issue if there's a feature you feel the package is missing!

I'd really appreciate it if you'd take a look and share it with anyone who might find the package useful, and leave a star if you're feeling generous 😉

Top comments (0)