Filter an Array with Multiple Conditions in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20212 min read

banner

Photo by Sergey Zolkin

Filter an Array with Multiple Conditions in JavaScript #

To filter an array with multiple conditions:

  1. Call the Array.filter method, passing it a function
  2. The function should use the && (And) operator to check for the conditions
  3. Array.filter returns all elements that satisfy the conditions
index.js
// Supported in IE 9-11 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 will get invoked with each element in the array.

If the function returns a truthy value, the array element is included in the results array.

In the code snippet 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.

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);

In the code snippet, we check for two conditions using the || operator.

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

In our example, 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee