查找 Javascript 中最常见的单词

Finding the most common word in Javascript

它目前可以找到第一个重复次数最多的单词,现在我需要它在更多单词被使用时抓取多个单词。我的代码失败的部分是当我 split() 分隔单词然后 Set() 删除重复项时。我认为我的问题来自从字符串切换到数组?我只需要一个简单的方法来让它工作,任何建议都将受到赞赏。谢谢!

let str = "She she sells sea shells down by the sea shore boop seasalt"

function commonWord(){
    if (str.length === 0) {
        return null
    }

    str = str.toLowerCase()
    let maxCount = 0
    let maxWord = ""
    str = str.split(" ")
    str.forEach(word=>{
        let wordValue = str.filter(w => w === word).length
        
        if(wordValue > maxCount){
            maxCount = wordValue
            maxWord = word
        }
        else if(wordValue == maxCount){
            maxWord = maxWord + " " + word
            maxWord = maxWord.split(" ")
            maxWord = [...new Set(maxWord)]
        }
    })
        
        

    console.log(maxWord)
}

commonWord()

在我看来,最简单的方法就是使用数组开头:

let str = "She she sells sea shells down by the sea shore boop seasalt"

function commonWord(){
    if (str.length === 0) {
        return null
    }

    str = str.toLowerCase()
    let maxCount = 0
    let maxWord = []
    str = str.split(" ")
    str.forEach(word=>{
        let wordValue = str.filter(w => w === word).length
        
        if(wordValue > maxCount){
            maxCount = wordValue
            maxWord.length = 0
            maxWord.push(word)
        }
        else if(wordValue == maxCount){
            maxWord.push(word)
        }
    })
        
        

    console.log(maxWord)
}

commonWord()

如果有什么不对,我很糟糕,我对 js 很陌生。

一旦您不仅要查看最大值而且要查看“最大值”列表,那么在构建列表时存储迄今为止出现频率最高的单词将会有所帮助:

let str = "She she sells sea shells down by the sea shore boop seasalt"

let max = 0;
const ob = str.toLowerCase().split(' ').reduce((obj,cur) => {
  if (obj[cur]){
    obj[cur]++;
  } else {
    obj[cur] = 1;
  }
  if (max < obj[cur]) max = obj[cur];
  return obj}
  ,{})
console.log(ob)
const final = Object.entries(ob).filter(([k,v]) => v === max).flatMap(([k,v]) => k)
console.log(final)

  

在@Mulan 建议使用地图后:

let str = "She she sells sea shells down by the sea shore boop seasalt"

let max = 0;
const mymap = str.toLowerCase().split(' ').reduce((obj,cur) => {
  let currentVal = obj.get(cur);
  if (currentVal){
    obj.set(cur,++currentVal);
  } else {
    obj.set(cur,1);
  }
  if (max < currentVal) max = currentVal;
  return obj}
  ,new Map())

for (let [key, value] of mymap) {
  console.log(key + ' = ' + value)
}

const final = Array.from(mymap).filter(([k,v]) => v === max).flatMap(([k,v]) => k)
console.log(final)