Count the most frequently occurring elements in an array

function more(arr) {
    
    
        let max=null;//定义一个用来存储出现次数最多的元素
        let num=1;//定义一个用来存储最出现的次数
         arr.reduce((p,k)=>{
    
     //对该数组进行reduce遍历
             p[k]?p[k]++:p[k]=1;
                 if(p[k]>num){
    
    
                     num=p[k]
                     max=k
                 }
                 return p
        },{
    
    })
        return {
    
    max:max,num:num}//返回最多元素对象
    }

The idea of ​​this method is to convert the entire array into a pseudo-array object: the elements and the number of occurrences are stored as key-value pairs.

The second argument to reduce is the initial value passed to the function, and the first argument is a function. Then {} is passed to the p parameter for the first time in this method, and the k parameter is the currently traversed object, which is equivalent to the item parameter in Foreach.

Guess you like

Origin blog.csdn.net/wangxinxin1992816/article/details/132872446