比较搜索栏中两个带有部分字符串的单词数组

jfgube3f  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(391)

我是菜鸟,我试图学习设置搜索功能来查找含有配料的食谱,但我被部分字符串卡住了。。。
即使我键入部分字符串(如“苹果”表示“苹果”或“巧克力”表示“巧克力”),我也不想找到配方,但我不想只返回包含与输入匹配的完整配料列表的配方(如果有人键入“苹果汁”,他决不能找到“苹果派”)
即使输入的单词不完整,如何找到配方?如果有人能帮我。。。非常感谢。
我试着用一个简单的代码来解释我得到了什么:

const getRecipe = function (input, recipe){
recipe.forEach((ingredient) => {
        input.every((el) => recipe.includes(el)) ? console.log(recipe) : console.log("nothing found");
      })
}

const test1 = ["apple"]
const test2 = ["apples"]
const test3 = ["apples", "juice"]

getRecipe(test1, applePie);
getRecipe(test2, applePie);
getRecipe(test3, applePie);```
r6hnlfcb

r6hnlfcb1#

这将获取所有搜索键,并验证每个键是否可以分配给配方的一种成分。如果在配方的任何成分中都找不到匹配的搜索键,那么对于给定配方,代码将返回false。使用您的各种配方调用该方法,您将得到所有匹配的配方。

const recipeMatchesIngredients = function (input, recipe){
  return input.every((el) => (recipe.find((ingredient) => ingredient.startsWith(el))));
}

const applePie = ["apples", "flower"];

console.log(recipeMatchesIngredients(["app", "flower"], applePie)); // true
console.log(recipeMatchesIngredients(["app", "powder"], applePie)); // false
console.log(recipeMatchesIngredients(["apples", "juice"], applePie)); // false
console.log(recipeMatchesIngredients(["app", "flower", "pow"], applePie)); // false
z31licg0

z31licg02#

您可能希望改进搜索词典的数据结构,这将大大简化您的代码,而不考虑您的语言。比如说,如果您使用此数据结构:

const cookbook = [
{
  recipe : "apple pie",
  ingredients: ["apple", "pie"]
},
{
  recipe : "apple juice",
  ingredients: ["apple", "juice"]
},
{
  recipe : "milk shake",
  ingredients: ["milk", "shake"]
},
{
  recipe : "chocolate",
  ingredients: ["cocoa", "sugar"]
}
]

然后,您的搜索将大大简化为:

// will return the recipe that has "apple" in it's recipe key search
const relevantRecipe = cookbook.filter((cooks) => cooks.recipe.includes("apple"))
console.log(relevantRecipe)

相关问题