我正在寻找一种通过其元素的出现对数组进行排序的优雅方法.
例如,在:
['pear', 'apple', 'orange', 'apple', 'orange', 'apple']
输出应该是这样的
['apple', 'orange', 'pear']
我试图遍历数组并将事件保存在另一个临时数组中,但这个解决方案非常糟糕.
这需要两个循环.
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);