Filter an Array with Multiple Conditions in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Filter an Array with Multiple Conditions in JavaScript #

To filter an array with multiple conditions:

  1. Call the Array.filter() method on the array.
  2. Use the && (And) operator to check for multiple conditions.
  3. The Array.filter() method will return all elements that satisfy the conditions.
index.js
const people = [ {name: 'Adam', age: 30}, {name: 'Bob', age: 40}, {name: 'Carl', age: 30}, ]; const results = people.filter(element => { // 👇️ using AND (&&) operator return element.age === 30 && element.name === 'Carl'; }); // 👉️ [ {name: 'Carl', age: 30} ] console.log(results);

The function we passed to the Array.filter() method gets invoked with each element in the array.

If the function returns a truthy value, the corresponding array element gets added to the results array.

We check for multiple conditions, using the && (and) operator.

The element will only be added to the filtered array if both of the conditions are met.

The function in the example checks whether the current object has an age property with a value of 30 and a name property with a value of Carl.

If the callback function never returns a truthy value, then Array.filter returns an empty array.

If you need to filter an array with multiple conditions where only one condition has to be satisfied, use the Array.filter() method with the || (or) operator.

index.js
const people = [ {name: 'Adam', age: 30}, {name: 'Bob', age: 40}, {name: 'Carl', age: 30}, ]; const results = people.filter(element => { // 👇️ using OR (||) operator return element.age === 40 || element.name === 'Carl'; }); // 👉️ [{name: 'Bob', age: 40}, {name: 'Carl', age: 30}] console.log(results);

We used the OR || operator to check for multiple conditions.

If either of the conditions returns a truthy value, the corresponding element will be included in the results array.

In the code sample, we check for objects with the property age equal to 40 or objects with the property name equal to Carl.

There are 2 elements in the array that satisfy at least one of the 2 conditions, so Array.filter returns both of them.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.