检查一个数组的元素是否包含在另一个数组的元素中

Checking if elements of an array are included in elements of another array

我正在尝试匹配 2 个数组并检查第一个数组的所有元素是否都包含在第二个数组中。

我的第一个数组看起来像这样,它包含一系列选定的成分

selectedOptions:  Array [
  "egg",
  "spaghetti",
  "cream",
]

第二个数组包含一道菜的食谱,看起来像这样

"ingredients": Array [
    "spaghetti",
    "raw egg",
    "double cream",
    "tomato sauce",
]

现在,我有一个循环访问对象数组的函数,每个对象都包含“成分”数组

这是代码

const availableRecipes = recipeList.filter(function (item, i) {
      if (
        selectedOptions.some((option) =>
          item.ingredients.includes(option)          
        )        
      ) {
        return true;
      } else false;
    });

这个函数工作正常,因为它循环遍历我的食谱数组并检查每个项目是否“鸡蛋”和“意大利面”是每个食谱的一部分。

问题

该函数仅 return 如果食谱完全包含整个单词,即“鸡蛋”或“奶油”,则为真。 在我的示例食谱中,它将 return 错误,因为它不包含“鸡蛋”,而是包含“生鸡蛋”和“双层奶油”而不是“奶油”。

我认为问题在于在 item.ingredients.includes(option)

中使用 includes

无论如何我可以进行部分匹配吗?

您将需要另一个 .some,以遍历每个字符串以查看是否包含子字符串:

const availableRecipes = recipeList.filter((item) => {
  return selectedOptions.some(
    option => item.ingredients.some(
      ingredient => ingredient.includes(option)          
    )
  );
});

为了保持一致性,您还需要在最后 else 之后 return false;,而不是仅仅声明 else false;