Filter array of objects based on another array in javascript
Solution 1:
The simplest way to filter is to use the array's filter()
function, similar to this:
people.filter(person => id_filter.includes(person.id))
Solution 2:
You can use array.filter()
with few conditions to get the output you want. Also i have corrected your JSON.
var filtered = people.filter(function(item) {
return id_filter.indexOf(item.id) !== -1 && item.gender==='m';
});
DEMO
var people =[
{ "id": 1, "name": "abc", "gender": "m","age": "15" },
{ "id": 2, "name": "a", "gender": "m", "age": "25" },
{ "id": 3,"name": "efg", "gender": "f","age": "5" },
{ "id": 4,"name": "hjk","gender": "m","age": "35" },
{ "id": 5, "name": "ikly","gender": "m","age": "41" },
{ "id": 6, "name": "ert", "gender": "f", "age": "30" },
{ "id": 7, "name": "qwe", "gender": "f", "age": "31" },
{ "id":8, "name": "bdd", "gender": "m", "age": " 8" }
];
var id_filter = [1,4,5,8];
var filtered = people.filter(function(item) {
return id_filter.indexOf(item.id) !== -1 && item.gender==='m';
});
console.log(filtered);