strMaxItem查找字符串中出现频率最高的字母

function strMaxItem(str) {
  let countArr = []
  let strArr = str.split('')
  strArr.forEach(item => {
    let obj = countArr.filter(obj => {
      return item === obj['key']
    })[0]
    if (obj) {
      obj['count']++
    } else {
      obj = {
        key: item,
        count: 1
      }
      countArr.push(obj)
    }
  });
  let maxCount = 0
  let maxObjArr = []
  countArr.forEach(item => {
    if (item['count'] > maxCount) {
      maxCount = item['count']
      maxObjArr.splice(0, maxObjArr.length)
      maxObjArr.push(item)
    } else if (item['count'] === maxCount) {
      maxObjArr.push(item)
    }
  })
  return maxObjArr
}

猜你喜欢

转载自www.cnblogs.com/qq3279338858/p/9236366.html