美文网首页
统计字符串的字符出现次数并排序

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

作者: iien2121 | 来源:发表于2020-11-17 22:56 被阅读0次
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);

相关文章

网友评论

      本文标题:统计字符串的字符出现次数并排序

      本文链接:https://www.haomeiwen.com/subject/dgtqiktx.html