在 JavaScript 中找到句子中最頻繁出現的 n 個單詞
對於本問,我們定義一個句子是一個包含英文字母和標點的字串,而一個單詞是該句子的子串,由空格連線而成。
我們需要編寫一個 JavaScript 函式,該函式以句子字串 str 作為第一個引數,以一個數字 num 作為第二個引數。該函式首先應統計句子中每個單詞的頻率,然後返回一個長度為 num 的陣列,其中包含按頻率遞減放置的 num 個最頻繁單詞。
例如 −
如果輸入句子和數字為 −
const str = 'i am a good coder and i know that i can solve a problem'; const num = 2;
那麼輸出應為 −
const output = ['i', 'a'];
因為“i”在陣列中出現 3 次而“a”出現 2 次,它們是字串中最頻繁的 2 個單詞。
示例
程式碼如下 −
const str = 'i am a good coder and i know that i can solve a problem';
const num = 2;
const findMostFrequent = (str = '', num = 1) => {
const strArr = str.split(' ');
const map = {};
strArr.forEach(word => {
if(map.hasOwnProperty(word)){
map[word]++;
}else{
map[word] = 1;
}
});
const frequencyArr = Object.keys(map).map(key => [key, map[key]]);
frequencyArr.sort((a, b) => b[1] - a[1]);
return frequencyArr.slice(0, num).map(el => el[0]);
};
console.log(findMostFrequent(str, num));輸出
在控制檯中的輸出為 −
[ 'i', 'a' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP