查数组中重复最多的字段

Array.prototype.repeat = function(...indexArr){
  let shipObj = this.reduce((pre, cur)=>{
    pre[cur] ? pre[cur]++ : pre[cur] = 1;
    return pre;
  }, {})
  let valList = Object.values(shipObj).sort((m,n)=>n-m);
  if(!indexArr.length){
    indexArr = [0]
  }
  let resArr = indexArr.map(index=> valList[index]||null).filter(v=>v!==null)
  Object.keys(shipObj).forEach(key=>{
    resArr.some((val,i)=>{
      if(shipObj[key] === val){
        resArr[i] = [key, shipObj[key]];
        return true;
      }
      return false
    })
  })
  return resArr.length > 1 ? resArr : resArr[0]||[];
}

 

posted @ 2019-12-08 13:54  刘金宇  阅读(164)  评论(0编辑  收藏  举报