在 JavaScript 中查找出现次数最多的元素的出现次数

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 9:16:17

我们需要编写一个 JavaScript 函数,该函数接受一个文字数组并返回数组中出现次数最多的元素的数量。

示例

其代码为 −

let arr = [2, 8, 4, 8, 6, 4, 7, 8];
const countOccurence = arr => {
   const max = arr.reduce((acc, val) => {
      return Math.max(acc, val);
   }, -Infinity);
   const count = arr.filter(el => {
      return el === max;
   });
   const { length } = count;
   return length;
};
console.log(countOccurence(arr));

输出

控制台中的输出 −

3

相关文章


有用资源