EN
JavaScript - filter array using multiple conditions
3
points
In this article, we would like to show you how to filter an array using multiple conditions in JavaScript.
Practical example
In this example, we create an object containing conditions, then we use it to filter users array. The filter() method goes through all the keys in the users array returning only the objects that match the criteria.
// ONLINE-RUNNER:browser;
const conditions = {
name: 'Tom',
age: 25
};
const users = [
{ id: 1, name: 'Tom', age: 25 },
{ id: 2, name: 'Tom', age: 25 },
{ id: 3, name: 'Tom', age: 30 }
];
const result = users.filter((object) => {
for (const key in conditions) {
if (key in object && object[key] !== conditions[key]) return false;
}
return true;
});
console.log(JSON.stringify(result, null, 4));