Sort a Javascript Array by frequency and then filter repeats

前端 未结 8 1800
南笙
南笙 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 08:03

    for the first step to compute

    {
        oranges: 4,
        bananas: 2,
        apples: 1
    }
    

    you can use countBy function of underscroe.js

    var all=["apples", "oranges", "oranges", "oranges", "bananas", "bananas", "oranges"];
    var frequency=_.countBy(all,function(each){return each});
    

    so frequency object will contain frequency of all unique values, and you can get an unique list by simply calling _.uniq(all), and to sort that unique list by the _.sortBy method of underscore and using your frequency object you can use

    _.sortBy(_.uniq(all),function(frequencyKey){return -frequency[frequencyKey]});
    

    -ve sign is used here to sort the list in decending order by means of frequency value as per your requirement.

    You can check the the documentation of http://underscorejs.org/ for further optimization by your own trick :)

提交回复
热议问题