Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects dynamically according to another array of objects

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!!

like image 867
Ali Mir Avatar asked Mar 02 '26 04:03

Ali Mir


1 Answers

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.

like image 74
gog Avatar answered Mar 04 '26 18:03

gog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!