使用 JavaScript 查找数组中出现频率最高的单词
问题
我们需要编写一个JavaScript函数,它接受一个由英文小写字母组成的字符串数组arr作为第一个参数。我们函数的第二个参数是一个数字num(num 我们的函数应该返回数组arr中出现频率最高的num个元素。 答案应按频率从高到低排序。如果两个词具有相同的频率,则首先出现字母顺序较低的词。 例如,如果函数的输入是 输入const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"];
const num = 4;
输出
const output = ["the", "is", "sunny", "day"];
输出说明
“the”、“is”、“sunny”和“day”是四个最常用的词,
出现次数分别为4、3、2和1。
示例
以下是代码-
const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"]; const num = 4; const mostFrequent = (arr = [], num = 1) => { const map = {}; let keys = []; for (let i = 0; i < arr.length; i++) { if (map[arr[i]]) { map[arr[i]]++; } else { map[arr[i]] = 1; } } for (let i in map) { keys.push(i); } keys = keys.sort((a, b) => { if (map[a] === map[b]) { if (a > b) { return 1; } else { return -1; } } else { return map[b] - map[a]; } }) .slice(0, num); return keys; }; console.log(mostFrequent(arr, num));输出结果
[ 'the', 'is', 'sunny', 'day' ]