Filter an Array with Multiple Conditions in JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Filter an Array with Multiple Conditions in JavaScript #

To filter an array with multiple conditions:

  1. Use the Array.filter() method to iterate over the array.
  2. Use the logical 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 logical 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 logical 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.

2 elements in the array meet at least one of the 2 conditions, so the Array.filter() method returns both of them.

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.

Copyright ยฉ 2023 Borislav Hadzhiev