0

I have two array of objects, filter and users. i want to loop through each user and check if his name is matching the filter.

var filter = [
{name: 'John'},
{name:'Tom'}
]
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'
  }
];

I have tried this, but no luck.

users= users.filter(function(item) {
  filter.forEach(function (key) {
    if (item.name=== undefined || item.name == filter[key.name])
      return false;
  })
  return true;
});
console.log(users)

I'm looking for a result like.

[
  {
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  }
]
gumireddy
  • 51
  • 1
  • 2
  • 11
  • @zcoop98 `filter` is an array of objects. `filter[item.name]` will not work. They need to use `some` as [mentioned in the duplicate](https://stackoverflow.com/a/31005753): `users.filter(u => filter.some(f => f.name === u.name))` – adiga Aug 05 '20 at 17:17
  • You're exactly right, I had just noticed. That makes the second loop make more sense. – zcoop98 Aug 05 '20 at 17:18
  • Since only one property is being checked, you can create a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) of names for faster filter: `const names = new Set(filter.map(o => o.name))` and then `users.filter(u => names.has(u.name))` – adiga Aug 05 '20 at 17:20

0 Answers0