gpt4 book ai didi

javascript - 如何找到数组中元素与集合数组 node.js 的最佳匹配

转载 作者:行者123 更新时间:2023-11-30 20:21:04 25 4
gpt4 key购买 nike

设置数组:

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
}
}
}

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

最佳答案

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

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

关于javascript - 如何找到数组中元素与集合数组 node.js 的最佳匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51447817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com