【问题标题】:Compare two arrays of word with partial string for search bar将两个单词数组与搜索栏的部分字符串进行比较
【发布时间】:2021-07-09 15:38:28
【问题描述】:

我是新手,我尝试学习设置搜索功能以查找带有成分的食谱,但我被部分字符串卡住了......

即使我输入部分字符串,我也想找到食谱(例如“apples”的“apple”或“chocolate”的“choc”),但我只想返回具有与输入匹配的完整成分列表的食谱(如果有人输入“苹果汁”,他一定找不到“苹果派”)

即使输入的单词作为菜谱的成分不完整,如何找到菜谱?

如果有人可以帮助我...

谢谢

我试着写一个简单的代码来解释我到目前为止得到了什么:

const applePie = ["apples", "pie"]
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);

【问题讨论】:

  • 尝试在 getRecipe 函数中将输入修改为new Array(input.join(" "))
  • 什么都没有改变...

标签: javascript arrays search partial


【解决方案1】:

这会获取所有搜索键,并验证每个键是否可以分配给配方的一种成分。如果在食谱的任何成分中都找不到与搜索键匹配的内容,则代码将为给定的食谱返回 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

【讨论】:

  • 你的逻辑看起来不错,但我的食谱是这样列出的:jsfiddle.net/qot1y0xa 我找不到如何适应它(因为对象中的“ingredient.ingredient”东西)
  • 好的,我找到了适应方法,非常感谢!!
【解决方案2】:

您可能希望改进搜索字典的数据结构,这将大大简化您的代码,无论您使用哪种语言。所以,比如说,如果你有这个数据结构:

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)

【讨论】:

  • 其实我的 json 是这样的:jsfiddle.net/xoufd4gv/14 我不能应用包含在它上面...
  • 哦好吧,看来你已经找到答案了,但正如你在问题中所说,你是新手,所以我以为你在做实验什么的,不管...请下次在您的问题中添加此类上下文,当您得到答案时它将有很大帮助
猜你喜欢
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多