Sort a Javascript Array by frequency and then filter repeats

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

    Let me put a minimal code to get unique values (and with frequencies) in ES6.

    var arr = ["apples", "oranges", "oranges", "oranges", "bananas", "bananas", "oranges"];
    console.log([...new Set(arr)])

    It is also applied to array of objects to aggregate some properties.

    var arr = [{"fruit":"apples"}, {"fruit":"oranges"}, {"fruit":"oranges"}, {"fruit":"oranges"}, {"fruit":"bananas"}, {"fruit":"bananas"}, {"fruit":"oranges"}];
    console.log(arr.reduce((x,y)=>{if(x[y.fruit]) {x[y.fruit]++;return x;} else {var z={};z[y.fruit]=1;return Object.assign(x,z);}},{}))

    0 讨论(0)
  • 2020-12-13 08:09

    // returns most frequent to least frequent

    Array.prototype.byCount= function(){
        var itm, a= [], L= this.length, o= {};
        for(var i= 0; i<L; i++){
            itm= this[i];
            if(!itm) continue;
            if(o[itm]== undefined) o[itm]= 1;
            else ++o[itm];
        }
        for(var p in o) a[a.length]= p;
        return a.sort(function(a, b){
            return o[b]-o[a];
        });
    }
    

    //test

    var A= ["apples","oranges","oranges","oranges","bananas","bananas","oranges"];
    A.byCount()
    

    /* returned value: (Array) oranges,bananas,apples */

    0 讨论(0)
提交回复
热议问题