Home > Net >  Filter array of multiple value
Filter array of multiple value

Time:01-13

This is my issue, I try to get result of items base on my filter array.

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

const items = [
{city: 'Boston', type: 'In Person'},
{city: 'New Jersey', type: 'In Person'},
{city:'Boston', type:'Virtual'}
]

const filteredResults = items.filter(el => papaFilter.some(filterEl => el[filterEl.type] === filterEl.value));

I want the first object of my items because papafilter contain Boston and In Person.

I know in my condition filterEl.value is an array of multiple value so this condition doesn't work. Any Ideas?

CodePudding user response:

You could filter the array by iteratirn the entries of the object and the filter array.

This approach takes an object for replacing keys.

const
    replacements = { type: 'event' },
    filter = [{ type: 'event', value: ['In Person'] }, { type: 'city', value: ['Boston', 'Miami', 'New York'] }],
    items = [{ city: 'Boston', type: 'In Person' }, { city: 'New Jersey', type: 'In Person' }, { city: 'Boston', type: 'Virtual' }],
    result = items.filter(o => Object.entries(o).every(([k, v]) =>
        filter.some(({ type, value }) => type === (replacements[k] || k) && value.includes(v))
    ));

console.log(result);

CodePudding user response:

I think you are looking for Array.includes. So, filterEl.value.includes(el[filterEl.type]) in the last block should give you the desired result.

You can find more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

  •  Tags:  
  • Related