How to Filter Array with Multiple Conditions in JavaScript

Updated onbyAlan Morel
How to Filter Array with Multiple Conditions in JavaScript

JavaScript comes with a built-in filter method on the Array class that helps you filter an array.

In this post, we'll learn how to you can use this method to filter an array using multiple conditions at the same time.

Using the filter method

Before we use it with multiple conditions, let's first use it with a single condition.

Let's start with a basic array of objects:

JAVASCRIPT
const array = [ { name: "John", age: 30 }, { name: "Jane", age: 25 }, { name: "Joe", age: 35 }, ];

Let's say we only wanted to get the names of the people who are 30 or older.

Let's use the filter method for this. This method takes a callback function that will be called for each element in the array, and if the callback returns true, the element will be included in the new array.

Here's an example using one condition:

JAVASCRIPT
const filtered = array.filter(element => element.age >= 30); console.log(filtered);
BASH
(2) [{…}, {…}] 0: {name: 'John', age: 30} 1: {name: 'Joe', age: 35}

As expected, because both John and Joe passed the condition, they were included in the new array.

Now let's move on to using multiple conditions.

Using multiple conditions

The filter method can be used with multiple conditions by using the && operator.

This operator essentially combines two conditions into one, allowing you to filter an array using multiple conditions.

Let's say we wanted to get the names of the people who are older than 20 but younger than 30.

JAVASCRIPT
const filtered = array.filter(element => element.age > 20 && element.age < 30); console.log(filtered);
BASH
0: {name: 'Jane', age: 25} length: 1

Just like before, because Jane was the only person with an age that passed both conditions, she was included in the new array, and nobody else.

Conclusion

In this post, we learned how you can use the filter method with multiple conditions by using the && operator to combine two separate conditions.

This allows you to filter an array as specifically as you want, giving you a lot of flexibility.

Hopefully, this helps you and thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.