Filter the objects that have the same field value of the value that we provide

My goal is to show only banners that have the same CODE provided in the KEYS array to filter. So I only want the banners which have the same code contained in the array KEYS. Thanks for the help.

const keys = ['343747', '213747', '123444']
export const banners = [
    {
    id: 1,
    name: 'Cashback',
    code: '343747',
    },
    {
    id: 2,
    name: 'Cosmetic',
    code: '213747',
    },
    {
    id: 3,
    name: 'Jeans',
    code: '123444',
    },
    {
    id: 4,
    name: 'WelcomeBonus',
    code: '54344',
    },
]

Number 4 has a code that is not present in the KEYS array so it shouldn’t be shown.

I tried to use the FILTER, REDUCE or MAP method but I couldn’t get to the solution. Thanks to anyone who can help me.

>Solution :

You can use const filteredBanners = banners.filter((banner) => keys.includes(banner.code))

filter will return an array of values from the original array that satisfies the given function.

Leave a Reply