You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中如何将传入食材数组与对象内食谱食材数组匹配筛选符合项

实现方案

核心是组合使用filter和every两个数组方法:

  • 用filter遍历整个食谱数组,筛选符合条件的条目
  • 对每个食谱的食材数组,用every判断所有食材是否都存在于传入的可用食材列表中

完整实现代码

// 入参:availableIngredients 可用食材数组,recipes 待筛选的食谱数组
function filterMatchedRecipes(availableIngredients, recipes) {
  return recipes.filter(recipe => {
    // 判断当前食谱的所有食材都在可用列表里
    return recipe._recipieIngridients.every(ingredient => 
      availableIngredients.includes(ingredient)
    )
  })
}

代入示例测试

const Ingridients = ['eggs', 'lemon']
const Recipies = [
  {
    _id:1,
    _recipieName:"Eggs and Lemon",
    _recipieIngridients:["eggs","lemon"]
  },
  {
    _id:2,
    _recipieName:"Onther Recipie",
    _recipieIngridients:["water","bread","blablabla"]
   }
]

const NewArray = filterMatchedRecipes(Ingridients, Recipies)
console.log(NewArray) // 输出结果和预期完全一致

可选调整说明

如果需求是食谱只要包含任意一种传入的食材就算符合条件,把every改成some即可。
如果需要忽略食材大小写匹配,可以在判断的时候统一转成小写/大写:

return recipe._recipieIngridients.every(ingredient => 
  availableIngredients.map(item => item.toLowerCase()).includes(ingredient.toLowerCase())
)

内容的提问来源于stack exchange,提问作者DavidB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:45:05