当前位置:  开发笔记 > 编程语言 > 正文

通过出现其元素对数组进行排序

如何解决《通过出现其元素对数组进行排序》经验,为你挑选了1个好方法。

我正在寻找一种通过其元素的出现对数组进行排序的优雅方法.

例如,在:

['pear', 'apple', 'orange', 'apple', 'orange', 'apple']

输出应该是这样的

['apple', 'orange', 'pear']

我试图遍历数组并将事件保存在另一个临时数组中,但这个解决方案非常糟糕.



1> epascarello..:

这需要两个循环.

    var arr = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
    //find the counts using reduce
    var cnts = arr.reduce( function (obj, val) {
        obj[val] = (obj[val] || 0) + 1;
        return obj;
    }, {} );
    //Use the keys of the object to get all the values of the array
    //and sort those keys by their counts
    var sorted = Object.keys(cnts).sort( function(a,b) {
        return cnts[b] - cnts[a];
    });
    console.log(sorted);
推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有