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

JavaScript筛选满足所有过滤条件的对象数组元素

JavaScript多条件全匹配筛选实现

需求为保留同时命中所有筛选项的条目,属于逻辑与(AND)匹配规则,可直接使用以下实现:

const filterRecipes = (recipeList, requiredIngredients) => {
  return recipeList.filter(recipe => {
    // 提取当前食谱的所有食材名生成集合,降低查找成本
    const ownedIngredients = new Set(recipe.ingredients.map(i => i.ingredient))
    // 校验所有必填食材是否都存在
    return requiredIngredients.every(ing => ownedIngredients.has(ing))
  })
}

// 调用示例
const myFiltersIngredients = ['farinha', 'frango']
const myRecipes = [
  {
    name: 'torta da vovo',
    ingredients: [
      { ingredient: 'farinha', ingredientUnit: 'grama(s)', ingredientQuantity: 500 },
      { ingredient: 'frango', ingredientUnit: 'grama(s)', ingredientQuantity: 500 }
    ]
  },
  {
    name: 'biscoito',
    ingredients: [
      { ingredient: 'farinha', ingredientUnit: 'grama(s)', ingredientQuantity: 500 },
      { ingredient: 'manteiga', ingredientUnit: 'grama(s)', ingredientQuantity: 500 }
    ]
  }
]

const result = filterRecipes(myRecipes, myFiltersIngredients)

核心逻辑说明

  • 遍历原始食谱数组时,对每个食谱先提取它包含的所有食材名称,存入Set结构做快速查找,比循环数组判断效率更高
  • 用Array.every()方法做全条件校验:只有筛选条件数组里的每一项都在当前食谱的食材列表中存在,该条目才会被保留
  • 不会出现只匹配单个筛选项就通过的问题,完全匹配「必须满足全部筛选项」的要求

结果验证

上述代码运行后,result数组只会保留name为torta da vovo的条目,仅含farinha不含frango的biscoito条目会被过滤,和预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.22 16:12:25