实现支持部分字符串匹配的食谱食材全匹配搜索功能求助
解决食材部分匹配+输入项全匹配的食谱搜索问题
嘿,作为编程新手能想到做这个功能已经很棒啦!先帮你梳理下现有代码的问题,再一步步实现你要的需求~
现有代码的问题
你当前的代码逻辑有几个小问题:
- 用
recipe.forEach遍历食谱食材完全没必要,我们要判断的是整个食谱是否符合条件,不是单个食材 input.every((el) => recipe.includes(el))是在做完全字符串匹配,没法实现你要的“apple匹配apples”这种部分匹配- 每次循环都输出结果,会导致重复打印
需求拆解与实现思路
咱们要实现的核心逻辑是:
- 对输入的每一个关键词,食谱里至少有一个食材包含这个关键词(部分匹配)
- 只有当所有输入关键词都满足上面的条件时,才返回这个食谱
修正后的代码实现
// 示例食谱数据 const applePie = ["apples", "pie crust", "sugar"]; const chocolateSmoothie = ["chocolate milk", "banana", "ice cubes"]; // 辅助函数:检查单个关键词是否能在食谱食材中找到部分匹配 const hasPartialMatch = (keyword, recipeIngredients) => { // 转成小写避免大小写问题(比如Apple和apples也能匹配) const lowerKeyword = keyword.toLowerCase(); return recipeIngredients.some(ingredient => ingredient.toLowerCase().includes(lowerKeyword) ); }; // 核心搜索函数 const getMatchingRecipes = (inputKeywords, allRecipes) => { // 筛选出满足所有输入关键词部分匹配的食谱 return allRecipes.filter(recipe => { return inputKeywords.every(keyword => hasPartialMatch(keyword, recipe)); }); }; // 测试用例 const test1 = ["apple"]; const test2 = ["apples"]; const test3 = ["apples", "juice"]; const test4 = ["choc"]; // 测试执行 console.log("Test1 结果:", getMatchingRecipes(test1, [applePie, chocolateSmoothie])); // 会返回applePie console.log("Test2 结果:", getMatchingRecipes(test2, [applePie, chocolateSmoothie])); // 会返回applePie console.log("Test3 结果:", getMatchingRecipes(test3, [applePie, chocolateSmoothie])); // 空数组(applePie没有juice相关食材) console.log("Test4 结果:", getMatchingRecipes(test4, [applePie, chocolateSmoothie])); // 会返回chocolateSmoothie
代码解释
hasPartialMatch函数:负责单个关键词的部分匹配,用some检查食谱里是否有食材包含这个关键词,同时转小写处理避免大小写敏感问题getMatchingRecipes函数:用filter遍历所有食谱,再用every确保每个输入关键词都能在食谱中找到部分匹配,只有满足所有条件的食谱才会被保留- 扩展了食谱数据,让测试用例更直观
额外优化建议
- 如果食谱数据量很大,可以考虑提前把食材转成小写存储,避免每次搜索都重复转换
- 可以给匹配结果加权重,比如完全匹配的食谱排在部分匹配的前面
内容的提问来源于stack exchange,提问作者Stampi
相关产品推荐
相关产品推荐

