【问题标题】:User input possibilities of pairs to match to arrays与数组匹配的用户输入对的可能性
【发布时间】:2021-01-01 16:53:49
【问题描述】:

我正在尝试在 javascript(我正在使用 node.js)中找到最有效的方法来获取用户的输入并将输入配对以找到精确的数组匹配项。我知道如何在不考虑性能的情况下做到这一点,我的主要目标是最好的性能算法。

例如: 用户输入(最多可以有 15 个动物):dog bear cat lion snake

api数据(json格式),其中动物数组长度始终为2:

{
  data: [
   { animals: ["cat", "dog"], content: "demo content 1." },
   { animals: ["snake", "cat"], content: "demo content 2." },
   { animals: ["bird", "mouse"], content: "demo content 3." }
  ]
}

我想找到所有的动物匹配,在这种情况下,用户输入将匹配到dog catcat snakeanimals。我将能够访问“演示内容 1”。和“演示内容 2”。

【问题讨论】:

    标签: javascript node.js arrays performance time


    【解决方案1】:

    一种相当有效的方法是在data 数组上使用Array.reduce,检查data.animals 中的每个值是否在用户输入中,如果是,则将内容推送到输出:

    const apidata = {
      data: [
       { animals: ["cat", "dog"], content: "demo content 1." },
       { animals: ["snake", "cat"], content: "demo content 2." },
       { animals: ["bird", "mouse"], content: "demo content 3." }
      ]
    }
    
    const userinput = ['dog', 'bear', 'cat', 'lion', 'snake']
    
    const content = apidata.data.reduce((c, o) => {
      if (o.animals.every(a => userinput.includes(a)))
        c.push(o.content);
      return c;
    }, []);
    
    console.log(content)

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2016-07-28
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多