Javascript:在字符串中查找单个字母出现次数最多的单词

时间:2013-06-26 21:02:55

标签: javascript string function character

我已经有了这个功能来逐字逐句地分隔字符串:

function LetterCount(str) {
var words = str.split(" ");
var letters;
var i;
    for (var i = 0; i < words.length; i++) {
      letters = words[i].split("");
     }
}

此函数用于搜索字符串并计算每个字母:

function charFreq(s) {
  var i, j;
  var a = new Array();

  for (j = 0; j < s.length; j++) {
    for (i = 0; i < a.length; i++) {
        if (a[i][0] == s[j]) {
         a[i][1]++;
               break;
        }
    }

    if (i == a.length) {

      a[i] = [s[j], 1];
    }
  }

  return a;
}

挣扎着找出一种同步使用这些代码的方法来找出单词数组中哪个单词的重复次数最多。

2 个答案:

答案 0 :(得分:0)

我想这可以满足您的需求:

count = function(ary) { return [].reduce.call(ary, function(o, x) { return o[x] = (o[x]||0) + 1,  o }, {}) }

text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium lobortis arcu, eget rhoncus est commodo sit amet."

letter = "o"

max = text.split(" ").reduce(function(max, word) { return count(word)[letter] > count(max)[letter] ? word : max })

console.log(max) // "commodo"

一些有用的代码只适合我

// how to write `max(words, key=lambda w: max(Counter(w).values()))` in js

max = function(xs, key) {
    // strictly speaking, there's no need to be schwartzian here, but it's nicer this way
    return xs.map(function(x) {
        return [x, key ? key(x) : x]
    }).reduce(function(m, v) {
        return v[1] > m[1] ? v : m
    })[0];
}

counter = function(xs) {
    return [].reduce.call(xs, function(o, x) {
        return o[x] = (Number(o[x]) || 0) + 1, o
    }, {});
}

values = function(o) {
    return Object.keys(o).map(function(x) { return o[x] })
}

words = "foo bar bbarb foxx abc".split(" ")
word = max(words, function(w) { return max(values(counter(w)))})
// bbarb

答案 1 :(得分:0)

var all_words = str.split(' ');
var all_freq = all_words.map(charFreq);
var max_freq = 0;
var max_word;
for (var i = 0; i < all_freq.length; i++) {
    for (j = 0; j < all_freq[i].length; j++) {
        if (all_freq[i][j][1] > max_freq) {
            max_freq = all_freq[i][j][1];
            max_word = i;
        }
    }
}
console.log("Word with most repeats is "+all_words[max_word]);

DEMO