js找众数

690 阅读1分钟

之前好像是在ccf上看见的找众数题目

let arr = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1];
let count = [0];            //新数组计数用
arr.forEach(item => {
    if (!count[item]) {
        count[item] = 0;
    }
    count[item]++;
});
let max = Math.max.apply(null, count);
console.log(max);
console.log(count.findIndex(item => item == max));

打印结果