word frequency in javascript

后端 未结 6 1442
自闭症患者
自闭症患者 2020-12-05 16:57

\"enter

How can I implement javascript function to calculate frequency of each word in

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 17:29

    const sentence = 'Hi my friend how are you my friend';
    
    const countWords = (sentence) => {
        const convertToObject = sentence.split(" ").map( (i, k) => {
            return {
              element: {
                  word: i,
                  nr: sentence.split(" ").filter(j => j === i).length + ' occurrence',
              }
    
          }
      });
        return Array.from(new Set(convertToObject.map(JSON.stringify))).map(JSON.parse)
    };
    
    console.log(countWords(sentence));

提交回复
热议问题