Reputation: 457
I'm trying to match 2 arrays and check if all elements of the first array are included in the second one.
My first array looks like this and it contains a series of selected ingredients
selectedOptions: Array [
"egg",
"spaghetti",
"cream",
]
the second array contains the recipe of a dish and looks like this
"ingredients": Array [
"spaghetti",
"raw egg",
"double cream",
"tomato sauce",
]
Now, I have a function that iterates through an array of objects and each object contains the "ingredients" array
here is the code
const availableRecipes = recipeList.filter(function (item, i) {
if (
selectedOptions.some((option) =>
item.ingredients.includes(option)
)
) {
return true;
} else false;
});
this function works fine, in the sense that it loops through my recipe array and checks for each item if the "egg" and "spaghetti" are part of each recipe.
THE PROBLEM
The function only returns True if the recipe contains exactly the entire word i.e. "egg" or "cream". In my example recipe it will return False as it doesn't contain "egg" but "raw egg" and "double cream" instead of "cream".
I think the problem is with using includes in item.ingredients.includes(option)
Is there anyway that I can do a partial match?
Upvotes: 0
Views: 50
Reputation: 1386
For consistency, you'll also need to return false;
after your final else
, rather than just stating else false;
Upvotes: 0
Reputation: 370679
You'll need another .some
, to iterate over each string to see if the substring is included:
const availableRecipes = recipeList.filter((item) => {
return selectedOptions.some(
option => item.ingredients.some(
ingredient => ingredient.includes(option)
)
);
});
Upvotes: 1