Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Wed Apr 05 2023

Filter arrays in JavaScript

The ability to filter data based on different criterias are inevitabile in large projects, or small ones for that matter. The use cases are many, for example if you want to have a search input to search through data, or if you have for example tabs that you are using as filters based on a category for example.

The scenarios are many, and today we will take a look at how we can use Array.filter() to help us with our problems.

Basic example

We start simple, in our first example we will filter an array of numbers and we want to filter out all odd numbers.

const numbers = [4, 7, 8, 3, 5, 2]; const evenNumbers = numbers.filter((number) => number % 2 === 0); // [ 4, 8, 2 ]

NOTE: Just as we discussed in our Array.map() article, the filter() function will not affect the original array, it will do a copy of it with the new criteria applied. So in above example, numbers array will be intact and our evenNumbers will be a new array copied from numbers.

So doing this:

numbers.filter((number) => number % 2 === 0);

Won't have any affect on numbers array.

Search for a specific value

Let's take a look at another scenario. If we have an array of names and we want to have a function that search through the names based on a search input, how can that be solved?

Example:

const names = ["John", "Esther", "Jonathan", "Susan", "Louise"]; const search = (query) => { return names.filter((name) => name.toLowerCase().includes(query.toLowerCase()) ); }; console.log(search("Jo")); // [ 'John', 'Jonathan' ] console.log(search("e")); // [ 'Esther', 'Louise' ]

In this example, we are creating a function that will simply take the input value and see if it exists in any of the names array. We are doing toLowerCase() to avoid unnecessary errors with cases.

Filter arrays with objects

A common scenario is to filter arrays with objects. Let's have a look at one of those examples as well:

const invoices = [ { value: 500, status: "PAID" }, { value: 250, status: "NOT_PAID" }, { value: 10, status: "PAID" }, { value: 80, status: "NOT_PAID" }, ]; console.log(invoices.filter((invoice) => invoice.status === "NOT_PAID")); [ { value: 250, status: "NOT_PAID" }, { value: 80, status: "NOT_PAID" }, ];

Here we are filtering out all the PAID transactions and keeping the NOT_PAID ones.

Filter on nested objects

A not uncommon scenario can also be to filter on a value in an object that is inside another object, also called, a nested object. Let's have a look:

const customers = [ { name: "Gordon", invoices: [{ value: 500, status: "PAID" }], }, { name: "Jordan", invoices: [ { value: 80, status: "NOT_PAID" }, { value: 10, status: "PAID" }, ], }, { name: "Anna", invoices: [ { value: 50, status: "NOT_PAID" }, { value: 30, status: "PAID" }, ], }, , ]; const customersWithUnpaidInvoices = customers.filter( (customer) => customer.invoices.filter((invoice) => invoice.status === "NOT_PAID").length );

Result

[ { "name": "Jordan", "invoices": [ { "value": 80, "status": "NOT_PAID" }, { "value": 10, "status": "PAID" } ] }, { "name": "Anna", "invoices": [ { "value": 50, "status": "NOT_PAID" }, { "value": 30, "status": "PAID" } ] } ]

In above example, we filtered the customers array based on the filtered value of each invoices array.

Using predicates

Another case is that you might find yourself using the same type of logic around your application when it comes to filtering. Let's see how we can reuse our filter predicates:

const names = ["John", "Esther", "Jonathan", "Susan", "Louise"]; const cars = ["Tesla", "Volkswagen", "Dacia", "Volvo"]; const filterPredicate = (query) => (currentValue) => { return currentValue.toLowerCase().includes(query.toLowerCase()); }; console.log(names.filter(filterPredicate("S"))); // ["Esther", "Susan", "Louise"]; console.log(cars.filter(filterPredicate("Vo"))); // ["Volkswagen", "Volvo"];

In above example, we have broken out the predicate logic to a function and share it between different array types. This can be useful in cases where the arrays have the same structure and share similarities. Then we can avoid dulications in our code base.

Outro

In todays guide we shared some examples on how they Array.filter() function works and how we can apply it in our applications. Filter data is considered essential in most projects, and plays an important role in many cases. Especially when searching or grouping data for example.

I hope you learned something from this guide. Thanks for reading and have a good one!

signatureWed Apr 05 2023
See all our articles