javascript - 如何找到数组中元素与集合数组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
}
}
}
但似乎不能正常工作。需要最快但最好解释的解决方案[仅适用于复杂的情况哈哈]。
解决方案
您可以映射每个句子中每个单词的计数。稍后,您可以获取最大值的索引。
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);
推荐阅读
- java - 有没有办法将字符串变量放在图像视图中
- javascript - 考虑到您不知道 Flask/Mysql 中有多少输入文本,如何在表单中获取所有用户输入的数据
- c++ - 一个最令人头疼的案例
- docker - 访问托管在 Docker 容器中的 Go Api
- node.js - YouTube PlaylistItems API 在使用 JSON.parse() 时导致语法错误
- python - Tensoflow2 LSTM - 未使用的参数 input_shape?
- javascript - iframe 中如何禁用功能策略?
- python - 创建类的函数
- r - R:将因子变量级别的数据框组合成一个变量
- c++ - 当我初始化变量时,错误消息类型 int 是意外的