Home > Back-end >  Filter array of objects dynamically according to another array of objects
Filter array of objects dynamically according to another array of objects

Time:11-30

So I am making a filter functionality for React, so I have an array of objects, and based on another array that contains values to filter the array, I need to get the filtered values.

code: the array of objects to apply the filter to:

const citiesData = [
    {
        id: 1,
        name: 'amritsar',
        popu: '1200'
    },
    {
        id: 2,
        name: 'jalandhar',
        popu: '1300'
    },
    {
        id: 3,
        name: 'phagwara',
        popu: '1200'
    },
    {
        id: 4,
        name: 'ludhiana',
        popu: '1400'
    },
    {
        id: 5,
        name: 'mumbai',
        popu: '2000'
    },
    {
        id: 6,
        name: 'banglore',
        popu: '2000'
    },
    {
        id: 7,
        name: 'ohter city 1',
        popu: '1500'
    },
        {
        id: 8,
        name: 'ohter city 2',
        popu: '1500'
    },
    {
        id: 9,
        name: 'anohter city 1',
        popu: '2200'
    },
        {
        id: 10,
        name: 'anohter city 2',
        popu: '2200'
    },
    
]

code: filters array based on what I need to apply the conditions:

const filterCity = [
    {
        filterType: 'name',
        filterValue: 'amritsar'
    },
    {
        filterType: 'popu',
        filterValue: '1200'
    }
]

solutions I've tried:-

code: solution 1:

const filteredList = citiesData.filter(item => {
    return filterCity.filter(fItem => item[fItem.filterType] === fItem.filterValue).length
})

code: solution 2:

const filteredList = citiesData.filter(item => {
    return filterCity.reduce((acc, val) => {
        if(item[val.filterType] === val.filterValue) {
            acc = true
        }
        return acc;
    }, false)
})

code: result I'm getting:

[
    { id: 1, name: 'amritsar', popu: '1200' },
    { id: 3, name: 'phagwara', popu: '1200' } 
]

it's giving me two objects because according to the filters array I'm searching for the name and popu fields. but the expected result should be:

[ { id: 1, name: 'amritsar', popu: '1200' } ]

because the name and popu is similar in that but in the second object the name is not the same.

I want the code to check all the conditions and then give me the result. right now it's working on the individual filter and individual array item.

so can anyone help me on this!!

CodePudding user response:

so, it should be an AND filter (combining all conditions)?

res = citiesData.filter(d => 
    filterCity.every(f => d[f.filterType] === f.filterValue))

for the OR filter (any condition), replace every with some.

  • Related