在 JavaScript 中查詢文字字串中最常出現的三個單詞


題目

我們要求編寫一個 JavaScript 函式,它接受一個英文字串。我們的函式應該返回字串中最常出現的三個單詞。

示例

以下是程式碼 −

 線上演示

const str = 'Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted. Python source code is now available under the GNU General Public License (GPL)';
const findTopThree = (str = '') => {
   str = str
   .replace(/[^\w\s]|_/g, "")
   .replace(/\s+/g, " ")
   .toLowerCase();
   const arr = str.split(' ');
   const map = {};
   arr.forEach(word => {
      map[word] = (map[word] || 0) + 1;
   });
   const res = Array.from(Object.keys(map), key => [key, map[key]]);
   res.sort((a, b) => b[1] - a[1]);
   return [res[0][0], res[1][0], res[2][0]];
};
console.log(findTopThree(str));

輸出

以下是控制檯輸出 −

["python","the","and"]

更新日期: 2021 年 4 月 20 日

402 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.