【问题标题】:How to find best match of element within array to a set array node.js如何找到数组中元素与集合数组node.js的最佳匹配
【发布时间】:2018-12-29 01:51:15
【问题描述】:

设置数组:

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

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

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

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

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

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

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

【问题讨论】:

  • 什么定义了与arr 匹配的allArr 的最佳元素?
  • 在这种情况下,它将是 index[1],因为它包含了大部分 arr[x]

标签: javascript arrays node.js for-loop


【解决方案1】:

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

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);

【讨论】:

  • 我认为它尽可能简单
猜你喜欢
  • 2012-07-13
  • 1970-01-01
  • 2018-03-16
  • 2017-01-24
  • 2018-01-23
  • 2021-11-03
  • 2015-05-23
  • 2012-04-27
  • 1970-01-01
相关资源
最近更新 更多