Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
To filter an array with multiple conditions:
Array.filter()
method to iterate over the array.&&
operator to check for multiple conditions.Array.filter()
method will return all elements that satisfy the
conditions.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.
&&
(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.
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.
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.