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

时间:2018-03-09 14:46:54

标签: javascript arrays

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

例如

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是单词,all都是字符串数组。

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

任何gud或替代方式

3 个答案:

答案 0 :(得分:1)

我在想这样的事情(虽然可能是更好的方式):

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

答案 1 :(得分:1)

尝试此解决方案

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

答案 2 :(得分:1)

这取决于你是否想要找到独特的单词,或者是否还要计算重复...正则表达式可以进行计数。

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