js查找出现次数最多的字符并统计次数

2021-04-09 06:11
1769
0
1
JavaScript

“ 给定一个字符串,找出出现次数最多的字符并统计次数 ”

直接上代码:

复制代码
function findMaxCountStr(str) {
        const arr = str.split('')
        const obj = {}
        let result = {}
        arr.forEach(e => {
            obj[e] = { key: e, count: obj[e] ? obj[e].count : 0  }
            if (Object.keys(obj).indexOf(e) > -1) {
                obj[e].count = !obj[e].count ? 1 : (obj[e].count + 1)
            } else {
                obj[e].count = 0
            }
        })
        const counts = Object.values(obj).map(e => e.count)
        const max = Math.max.call(null, ...counts)
        for (let i in obj) {
            if (obj[i].count === max) {
                result = obj[i]
            }
        }
        return result
    }
赏
支付宝微信
1
关注公众号获取更多内容
js递归数组去重方法
uniapp读取复制pages.json成为路由文件
暂无评论,快抢沙发吧
不支持canvas