Sort a Javascript Array by frequency and then filter repeats

前端 未结 8 1789
南笙
南笙 2020-12-13 07:06

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

8条回答
  •  执笔经年
    2020-12-13 07:45

    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; });
     }
    

提交回复
热议问题