What is an elegant way to take a javascript array, order by the frequency of the values, and then filter for uniques?
So,
[\"apples\", \"oranges\", \"o
Basic strategy:
Create an object to use as a hash table to track the frequency of each item in the array to be sorted.
Create a new array containing the item, frequency pairs.
Sort this array on frequency in descending order.
Extract the items from that array.
Code:
function descendingUniqueSort(toBeSorted) {
var hash = new Object();
toBeSorted.forEach(function (element, index, array) {
if (hash[element] == undefined) {
hash[element] = 1;
}
else {
hash[element] +=1;
}});
var itemCounts = new Array();
for (var key in hash) {
var itemCount = new Object();
itemCount.key = key;
itemCount.count = hash[key];
itemCounts.push(itemCount);
}
itemCounts.sort(function(a,b) { if(a.countb.count) return -1; else return 0;});
return itemCounts.map(function(itemCount) { return itemCount.key; });
}