基于可用食材及允许缺失数量的JavaScript食谱过滤实现
解决方案
我们可以通过统计每个食谱中未在家中备齐的食材数量,将其与允许缺失的阈值对比,来筛选符合条件的食谱,全程不会修改原有数据结构。
代码实现
// 示例数据结构 const recipes = [ { name: 'recipe1', ingredients: ['flour', 'sugar', 'eggs'] }, { name: 'recipe2', ingredients: ['flour', 'milk', 'eggs'] }, { name: 'recipe3', ingredients: ['butter', 'cream', 'vanilla'] } ]; const availableIngredientsAtHome = ['flour', 'sugar', 'eggs']; // 过滤函数 const filterRecipes = (recipes, availableIngredients, maxAllowedMissing) => { // 浅拷贝食谱对象,避免修改原数据 return recipes.map(recipe => ({ ...recipe })) .filter(recipe => { // 计算当前食谱中缺失的食材数量 const missingIngredientsCount = recipe.ingredients .filter(ingredient => !availableIngredients.includes(ingredient)) .length; // 判断缺失数量是否在允许范围内 return missingIngredientsCount <= maxAllowedMissing; }); }; // 测试场景1:允许缺失1种食材 let numberOfIngredientsRecipeCanMiss = 1; console.log(filterRecipes(recipes, availableIngredientsAtHome, numberOfIngredientsRecipeCanMiss)); // 输出:[{name: 'recipe1', ...}, {name: 'recipe2', ...}] // 测试场景2:不允许缺失食材 numberOfIngredientsRecipeCanMiss = 0; console.log(filterRecipes(recipes, availableIngredientsAtHome, numberOfIngredientsRecipeCanMiss)); // 输出:[{name: 'recipe1', ...}]
关键细节说明
- 不修改原数据:通过
{ ...recipe }浅拷贝每个食谱对象,确保原始的recipes数组及其内部对象不会被改动 - 缺失食材统计:使用数组的
filter方法筛选出不在可用食材列表中的食材,再通过length获取数量 - 阈值判断:仅保留缺失食材数小于等于
maxAllowedMissing的食谱
内容的提问来源于stack exchange,提问作者robtot
相关产品推荐
相关产品推荐

