Home > Software engineering >  javascript how to filter array for multiple condition
javascript how to filter array for multiple condition

Time:09-26

This is the filter:

var filter = {
  address: ['England'],
  name: ['Mark', 'Tom'] // Mark or Tom in this case
};
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'
  }
];

The filtered result should be

  {
    name: 'Tom',
    email: '[email protected]',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: '[email protected]',
    age: 28,
    address: 'England'
  }

CodePudding user response:

You take your users, filter it, and see if the name is contained in the filters.

const onlyMarkAndTom = users.filter(user => filter.name.includes(user.name))

Include additional conditions to narrow down the result

const onlyMarkAndTom = users.filter(user => filter.name.includes(user.name) && ...)

CodePudding user response:

users.filter((user) => {
  if (!filter.address.includes(user.address)) {
    return false;
  }
  if (!filter.name.includes(user.name)) {
    return false;
  }
  return true;
});
  • Related