'filtering an object array on a feild that is an array , by using an array
Lets say I have the two following arrays. The goal here is to filter "foods" array with the values of "tagsValues". I want to return a new array of foods, where foods.tags include one or several items from tagsValues.
const tagsValues = ['gluten-free', 'carb-free', 'flavor-free'];
const foods = [
{ name: 'pasta', tags: ['delicious', 'has carbs']},
{ name: 'gluten-free-pizza', tags: ['gluten-free']},
{ name: 'soda', tags: ['delicious', 'has sugars']},
{ name: 'pizza', tags: ['delicious', 'best meal of the year','carb-free']},
{ name: 'rice cakes', tags: ['flavor-free','carb-free']}
]
In this example , I need to get the following result :
result = [
{ name: 'gluten-free-pizza', tags: ['gluten-free']},
{ name: 'pizza', tags: ['delicious', 'best meal of the year','carb-free']},
{ name: 'rice cakes', tags: ['flavor-free','carb-free']}
]
So far I have tried the following. It seems to work only if there is only one value in foods.tags and that's a problem since most of the time foods.tags will have several items.
result= foods.filter(obj => {
return (
[...obj.tags].some(item => tagsValues.includes(item))
)})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
