user3673623 user3673623 - 4 months ago 9
Javascript Question

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: 'johnson@mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom@mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark@mail.com',
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.

Answer

you can do like this

var filter = {address: 'England', name: 'Mark'};
users = users.filter(function(item) {
    for(var key in filter) {
        if(item[key] === undefined || item[key] != filter[key])
            return false;
    }
    return true;
});
Comments