js方式找出数组中重复数最多的那个数,并返回该数以及重复次数

699 阅读1分钟

js方式找出数组中重复数最多的那个数,并返回该数以及重复次数

function findNum(a){
    let res = [0,0];//定义一个数组,存放结果
    for(let i = 0; i < a.length; i++) {
        for(j = 0, count = 0; j < a.length; j++) {
            if(a[i] == a[j]){
                ++count;//找到一个重复的项,计数器就 +1
            }
        }
      
        if(count > res[0]) {
            res[0] = count;
            res[1] = a[i];
        }else if(count == res[0] && res[1] < a[i]) {
            res[1] = a[i];
        }
    }
    alert("重复最多的是" + result[1] + ",重复了" + result[0] + "次");
}