【问题标题】:Checking if elements of an array are included in elements of another array检查一个数组的元素是否包含在另一个数组的元素中
【发布时间】:2021-01-30 08:38:30
【问题描述】:

我正在尝试匹配 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;
    });

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

问题

仅当配方包含完整的单词,即“egg”或“cream”时,该函数才返回 True。 在我的示例食谱中,它将返回 False,因为它不包含“egg”而是“raw egg”和“double cream”而不是“cream”。

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

中使用 includes

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

【问题讨论】:

    标签: javascript arrays multidimensional-array string-matching


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      为了保持一致,您还需要在最后的else 之后加上return false;,而不是只写else false;

      【讨论】:

      • 感谢您发现它!
      猜你喜欢
      • 2017-03-03
      • 2022-01-02
      • 2020-11-21
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      相关资源
      最近更新 更多