javascript filter array multiple conditions
I want to simplify an array of objects. Let's assume that I have following array:
var users = [{
name: 'John',
email: '[email protected]',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: '[email protected]',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: '[email protected]',
age: 28,
address: 'England'
}];
And filter object:
var filter = {address: 'England', name: 'Mark'};
For example i need to filter all users by address and name, so i do loop through filter object properties and check it out:
function filterUsers (users, filter) {
var result = [];
for (var prop in filter) {
if (filter.hasOwnProperty(prop)) {
//at the first iteration prop will be address
for (var i = 0; i < filter.length; i++) {
if (users[i][prop] === filter[prop]) {
result.push(users[i]);
}
}
}
}
return result;
}
So during first iteration when prop - address
will be equal 'England'
two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name
will be equal Mark
only the last user should be added to array result, but i end up with two elements in array.
I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it. Any help is appreciable. Thanks.
You can do like this
var filter = {
address: 'England',
name: 'Mark'
};
var users = [{
name: 'John',
email: '[email protected]',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: '[email protected]',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: '[email protected]',
age: 28,
address: 'England'
}
];
users= users.filter(function(item) {
for (var key in filter) {
if (item[key] === undefined || item[key] != filter[key])
return false;
}
return true;
});
console.log(users)
If you know the name of the filters, you can do it in a line.
users = users.filter(obj => obj.name == filter.name && obj.address == filter.address)