获取字符重复出现次数,可返回出现次数相同的不同字符

2020-05-30  本文已影响0人  EasonChan94
class RepeatStr {
    constructor(str) {
        this.str = str;
        this.resultObj = {};
        this.resultArray = [];
        this.maxNumber = null;
        this.elArray = null;
    }

    getStrArr() {
        return this.str.split('').reduce(function (prev, next) {
            prev[next] = (prev[next] + 1) || 1;
            return prev;
        }, {});
    }

    getRepeatStrArr() {
        this.resultObj = this.getStrArr();
        for (let key in this.resultObj) {
            this.resultArray.push({[key]: this.resultObj[key]})
        }
    }

    getElArr() {
        this.getRepeatStrArr();
        this.maxNumber = Math.max.apply(null, Object.values(this.resultObj))
        this.elArray = this.resultArray.filter(e => {
            let key = Object.keys(e)[0];
            return e[key] === this.maxNumber;
        })
    }

    output() {
        this.getElArr();
        let str = '', num;
        if (!this.elArray.length) {
            console.log('字符串为空');
            return;
        }
        this.elArray.forEach(e => {
            let key = Object.keys(e)[0];
            str += key + ','
            num = e[key]
        })
        console.log(`出现次数最多的字符是${str} 出现次数是${num}次`)
    }

}

new RepeatStr('dsajkldsalkjdsaazzz2222').output();
上一篇下一篇

猜你喜欢

热点阅读