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.
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.
xxxxxxxxxx
1
const conditions = {
2
name: 'Tom',
3
age: 25
4
};
5
6
const users = [
7
{ id: 1, name: 'Tom', age: 25 },
8
{ id: 2, name: 'Tom', age: 25 },
9
{ id: 3, name: 'Tom', age: 30 }
10
];
11
12
const result = users.filter((object) => {
13
for (const key in conditions) {
14
if (key in object && object[key] !== conditions[key]) return false;
15
}
16
return true;
17
});
18
19
console.log(JSON.stringify(result, null, 4));