Borislav Hadzhiev
Mon Oct 04 2021·2 min read
Photo by Sergey Zolkin
To filter an array with multiple conditions:
Array.filter
method, passing it a function&&
(And) operator to check for the conditionsArray.filter
returns all elements that satisfy the conditions// 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.
&&
(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.
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.
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.