在 JavaScript 中查找数组中出现频率最高的数字以及重复次数
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 17:16:17
我们需要编写一个 JavaScript 函数,该函数接受一个文字数组,并查找数组中出现频率最高的数字以及重复次数。
示例
其代码为 −
const arr = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
const findFrequency = (arr = []) => {
const count = {};
const max = arr.reduce((acc, val, ind) => {
count[val] = (count[val] || 0) + 1;
if (!ind || count[val] > count[acc[0]]) {
return [val];
};
if (val !== acc[0] && count[val] === count[acc[0]]) {
acc.push(val);
};
return acc;
}, undefined);
return {
max, count
};
}
console.log(findFrequency(arr));
输出
控制台中的输出将是 −
{
max: [ '4' ],
count: { '1': 3, '2': 2, '3': 2, '4': 5, '9': 1, '13': 1 }
}
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

