可以使用ES6的Map对象来实现。下面是一个示例代码:

const findMostFrequent = (arr) => {
  const countMap = new Map();
  let maxCount = 0;
  let mostFrequent;

  arr.forEach((item) => {
    const count = countMap.get(item) || 0;
    countMap.set(item, count + 1);

    if (count + 1 > maxCount) {
      maxCount = count + 1;
      mostFrequent = item;
    }
  });

  return mostFrequent;
};

const arr = [1, 2, 3, 2, 1, 1, 4, 2, 4, 2, 5];
const mostFrequentItem = findMostFrequent(arr);
console.log(mostFrequentItem); // 输出: 2

在上面的代码中,我们使用了一个Map对象countMap来记录每个元素出现的次数。遍历数组arr,对于每个元素,如果在countMap中已经存在,则将其出现次数加1;如果不存在,则将其添加到countMap中,并将其出现次数设置为1。在遍历过程中,我们还维护了一个变量maxCount来记录出现次数最多的元素出现的次数,以及一个变量mostFrequent来记录出现次数最多的元素。最后返回mostFrequent即可得到结果

ES6语法最简单的写一个数组中找一个出现次数最多的方法

原文地址: http://www.cveoy.top/t/topic/iv5T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录