【问题标题】:js - output the most matching listjs - 输出最匹配的列表
【发布时间】:2020-04-12 19:53:12
【问题描述】:

我是 JS 新手,需要一些帮助。 在这个例子中:我有一个列表,在这个列表中是一个数组中的“关键字”。

我找到了一些链接,但我现在不知道如何将其放入我的脚本中..

find String of an Array that is in an array

Javascript: Search for an array in an array of arrays

-> 所以我希望,当我搜索 ["apple", "strawberry"] 时,脚本会输出最匹配的列表。

这是我的想法,我尝试了很多东西..但没有像我预期的那样成功。


var groups = [
    {name: 'fruits', words:["apple","strawberry", "banana"]},
    {name: 'test', words:["asd","qwe"]}
];

var searchwords = ["apple", "strawberry"];

for(i = 0; i < groups.length; i++) {
    console.log(groups[i]);
    for(i = 0; i < searchwords.length; i++) {
        console.log(searchwords[i]);
        console.log('The most matching list is: ' + groups.name);
    }
}

输出应该是:

最好的组是“水果”组。

我想要一个列表(输出),像这样:

结果 = [2,0]

“2”代表列表“fruits”,因为其中有 2 个单词。 “0”用于列表“测试”,因为没有匹配的单词。

谢谢!

【问题讨论】:

标签: javascript arrays filter


【解决方案1】:

我不会给你完整的答案,但这是你应该做的。

for(i = 0; i < groups.length; i++){

}

这第一部分是正确的!您将遍历每个组。现在,您接下来需要做的是迭代当前组中的每个水果。

for(i = 0; i < groups.length; i++){
    for(j = 0; j < groups[i].words.length; ++j){

    }
}

这将使您可以访问当前组中的每个水果。现在,您需要找到一种方法来计算一个水果重复了多少次;也许你应该为此创建一个新字典。

自己动手试试,如果发现其他问题,请告诉我。

【讨论】:

  • 谢谢!我有一个错误:无法读取未定义的属性“长度”.. at groups[i].fruits.length
  • @DaveReiß 那是我的错;应该是groups[i].words.length!
【解决方案2】:

使用 kibe 首先提供的线索自行尝试。这是您可以做到的一种方式,我尽量保留您的原始代码并编写您想要的输出。希望能帮助到你!如果有什么不明白的地方/如果您需要任何解释,请告诉我。

var groups = [
    {name: 'fruits', words:["apple","strawberry", "banana"]},
    {name: 'test', words:["asd","qwe"]}
];

var searchwords = ["apple", "strawberry"];

// Initialize empty array with size equal to size of groups
var res = Array(groups.length).fill(0);
// Initialize variables to hold biggest number of matches and index of said matches
var biggestIndex;
var biggestValue = 0;

for(i = 0; i < groups.length; i++) {
    for(j = 0; j < groups[i].words.length; j++) {
        if(searchwords.includes(groups[i].words[j]) == true){
            res[i] += 1;
            if(res[i] > biggestValue){
                biggestValue = res[i];
                biggestIndex = i;
            }
        }
    }
}

// biggestIndex holds the index with the most matches
console.log("The best group is", groups[biggestIndex].name, "group");
// Res holds the list output you wanted
console.log(res);

https://jsfiddle.net/w9nqr02m/

【讨论】:

    【解决方案3】:

    有很多方法可以做到这一点。我更喜欢的一个:

    const result = groups.map(group => {
        const matchedwords = group.words.filter(word => searchwords.includes(word));
        return matchedwords.length;
    }
    

    PS:按照 kibe 的回答尝试解决您正在做的事情。如果您不熟悉它们,我还建议您查看 mapfilter 文档。它们在处理数组时非常方便。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 2016-11-26
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多