从字符串数组中获取具有最多单词数的元素



我有一个字符串数组和一个单词数组。我想从字符串数组中获取具有最多单词(单词数组中的单词(的元素。

例如

var words = ["mango", "apple"];
var strings = ["apple is gud", "mango and apple are both gud"]
someWeirdFunction(strings, words)
-> mango and apple are both gud

这是我做的笏。Q是单词,所有都是字符串数组。

var q = question.split(" ");
var max = 0;
var index = 0;
for(var i = 0; i < all.length; i++) {
    var txt = all[i];
    var wordsMatched = 0;
    for(var j = 0; j < q.length; q++) {
        var word = q[j];
        if(txt.indexOf(word) > -1) {
            wordsMatched++;
        }
    }
    if(i == 0) 
        max = wordsMatched;
    else
        max = Math.max(wordsMatched, max)
    if(wordsMatched === max)
        index = i;
}

任何 GUID 或其他方式

我在想这样的事情(不过可能是一个更好的方法(:

var words = ["mango", "apple"];
var strings = ["apple is gud", "mango and apple are both gud"];
console.log(getStringWithMostWords(strings, words));
function getStringWithMostWords(strings, words) {
    let biggestFound, found, output;
    biggestFound = 0;
    output = ``;
    strings.forEach(string => {
        found = 0;
        words.forEach(word => {
            // search for each word in each string
            if (string.indexOf(word) > -1) {
                found += 1;
            }
        });
        if (found > biggestFound) {
            // compare the number of words found in this string with the biggest number found so far
            biggestFound = found;
            output = string;
        }
    });
    return output;
}

试试这个解决方案

  var words = ["mango", "apple"];
  var strings = ["apple is gud", "mango and apple are both gud"];
  var index = strings.map((string)=>string.split(" ").filter((word)=>words.indexOf(word)>-1))
.map((arr)=>arr.length)
.reduce((crr,acc)=>crr> acc? crr: acc ,0)
 console.log(strings[index])

这取决于您是否要找到唯一的单词,或者是否也应该计算重复项......正则表达式可以进行计数。

var words = ["mango", "apple"];
var strings = ["apple is gud", "mango and apple are both gud"]
countWords(strings, words);
function countWords(str, wrd) {
  var reg = new RegExp(wrd.toString().replace(/,/g, '|'), 'g');
  var max = 0;
  var maxIndex = 0;
  for (var i = 0; i < str.length; i++) {
    var curLen = str[i].match(reg).length;
    if (curLen > max) {
      max = curLen;
      maxIndex = i;
    }
  }
  return str[maxIndex];
}

最新更新