Skip to content

JavaScript 出现频率最高的单词

Published: at 01:28 PMSuggest Changes

一言不合先贴代码

function findMoreWord(params) {
  let word = params.trim().toLocaleLowerCase();
  let wordList = word.match(/[a-z]+/g);
  let maxNumber = 0;
  let maxWord = '';
  wordList.reduce((acc, word) => {
    acc[word] ? (acc[word] += 1) : (acc[word] = 1);
    if (acc[word] > maxNumber) {
      maxNumber = acc[word];
      maxWord = word;
    }
    return acc;
  }, {});
  return maxWord;
}

console.log(findMoreWord('hello hi hi hi hello go good best'));

练习了一下 reduce 和简单的正则


Previous Post
JavaScript 实现简单的发布订阅模式
Next Post
JavaScript 红黄绿灯交替实现