JS_LnMstr
JS_LnMstr

Reputation: 378

Filter an array of objects by another array elements

I've tried to figure this out with another similar posts, but can't find the right way to do this:

i have this array:

let concessions = [
     {
        name: Auto Cars,
        brands: ['Ferrari', 'Seat', 'Kia']
     },
     {
        name: ParisCars,
        brands: ['Opel', 'Ford', 'Honda']
     },
]

and i have this another array:

let wantedCars = ['Ferrari', 'Toyota'];

I need to filter each object from the concessions array and create another array only with concessions that includes one or more brands that existes on wantedCars array. I've tried this:

let filteredConcessions = concessions.filter(concession => concessions.brands.includes(wantedCars))

but, return 0.

Any advice?

Upvotes: 0

Views: 26

Answers (1)

Ele
Ele

Reputation: 33726

You should use the function Array.prototype.some instead because you need to compare a property and not the whole object.

let filteredConcessions = concessions.
            filter(concession => concession.brands.some(b => wantedCars.includes(b)));

let concessions = [   {      name: "Auto Cars",      brands: ['Ferrari', 'Seat', 'Kia']   },   {      name: "ParisCars",      brands: ['Opel', 'Ford', 'Honda']   }],
    wantedCars = ['Ferrari', 'Toyota'],
    filteredConcessions = concessions.
            filter(concession => concession.brands.some(b => wantedCars.includes(b)));
            
console.log(filteredConcessions);

Upvotes: 2

Related Questions