filter array based on multiple condition

I would like to get the result of my event based on the filter.

const filter = [
  { type: 'type', value: ['In Person'] },
  { type: 'city', value: ['Boston', 'Miami', 'New York'] },
];

const events = [
  { node: { city: 'Boston', type: 'In Person', name: 'Boston Party' } },
  { node: { city: 'New Jersey', type: 'In Person', name: 'Hello Cookie' } },
  { node: { city: 'Boston', type: 'Virtual', name: 'Sales Kick Off' } },
];

const result = events.filter(o => Object
  .entries(o.node)
  .every(([k, v]) => filter
    .some(({ type, value }) => type === k && value.includes(v)),),)

console.log(result)

I want the first object of my events because filter contain Boston and In Person. (This function will work if I remove the key name on my events). How this function can return a result if i have more key and value on my events.


Solution 1:

You could filter with filter.

const
    filter = [{ type: 'type', value: ['In Person', 'Virtual'] }, { type: 'city', value: ['Boston', 'Miami', 'New York'] }],
    events = [{ node: { city: 'Boston', type: 'In Person', name: 'Boston Party' } }, { node: { city: 'New Jersey', type: 'In Person', name: 'Hello Cookie' } }, { node: { city: 'Boston', type: 'Virtual', name: 'Sales Kick Off' } }],
    result = events.filter(({ node }) =>
        filter.every(({ type, value }) => !value.length || value.includes(node[type]))
    );

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }