首页 > 解决方案 > 如何找到数组中元素与集合数组node.js的最佳匹配

问题描述

设置数组:

let arr = ["hello","my","name","connor"]

与 arr 比较的所有元素的数组:

let allArr = ["hello my name is", "hello my name is connor", "hello connor name"]

所以在这种情况下,我想要一个解决方案,选择allArr匹配的最佳元素arr,它的索引就足够了。

我尝试过集成两个 for 循环,例如

for (i in allArr){
  for(x in arr){
     if(allArr[i].includes(arr[x]){
        do something
     }
  } 
}

但似乎不能正常工作。需要最快但最好解释的解决方案[仅适用于复杂的情况哈哈]。

标签: javascriptarraysnode.jsfor-loop

解决方案


您可以映射每个句子中每个单词的计数。稍后,您可以获取最大值的索引。

var words = ["hello", "my", "name", "connor"],
    sentences = ["hello my name is", "hello my name is connor", "hello connor name"],
    counts = sentences.map(s => words.reduce((sum, word) => sum + s.includes(word), 0)),
    indices = counts.reduce((r, c, i, a) => {
        if (!(a[r[0]] >= c)) {
            return [i];
        }
        if (a[r[0]] === c) {
            r.push(i);
        }
        return r;
    }, []);
    
console.log(counts);
console.log(indices);


推荐阅读