Sort a Javascript Array by frequency and then filter repeats

前端 未结 8 1801
南笙
南笙 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:51

    I was actually working on this at the same time - the solution I came up with is pretty much identical to Anurag's.

    However I thought it might be worth sharing as I had a slightly different way of calculating the frequency of occurrences, using the ternary operator and checking if the value has been counted yet in a slightly different way.

    function sortByFrequencyAndFilter(myArray)
    {
        var newArray = [];
        var freq = {};
    
        //Count Frequency of Occurances
        var i=myArray.length-1;
        for (var i;i>-1;i--)
        {
            var value = myArray[i];
            freq[value]==null?freq[value]=1:freq[value]++;
        }
    
        //Create Array of Filtered Values
        for (var value in freq)
        {
            newArray.push(value);
        }
    
        //Define Sort Function and Return Sorted Results
        function compareFreq(a,b)
        {
            return freq[b]-freq[a];
        }
    
        return newArray.sort(compareFreq);
    }
    

提交回复
热议问题