统计字符串的字符出现次数并排序

2020-11-17  本文已影响0人  iien2121
let str = 'tongjillxxlxlfflxxlffxxx';
let obj = {};
for (let i in str) {
    let char = str.charAt(i);
    if (obj[char]) {
        obj[char]++;
    } else {
        obj[char] = 1;
    }
}
console.log('统计:', obj);
let newObj = {},
    newArr = [];
for (let i in obj) {
    let node = {};
    node[i] = obj[i];
    newArr.push(node);
}
newArr.sort((a, b) => {
    for (let i in a) {
        a = a[i]
    }
    for (let i in b) {
        b = b[i]
    }
    return b - a
})
console.log('排序:', newArr);
上一篇 下一篇

猜你喜欢

热点阅读