出于这个问题的目的,我们将句子定义为包含英文字母和标点符号的字符串,单词是该句子的子字符串,由空格连接在一起。
我们需要编写一个 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' ]