Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array by occurrence of its elements

I'm looking for an elegant way of sorting an array by the occurrence of its elements.

For example, in:

['pear', 'apple', 'orange', 'apple', 'orange', 'apple']

the output should look like

['apple', 'orange', 'pear']

I have tried to loop through the array and save the occurrence in another temporary array, but this solution was quite bad.

like image 314
Carle B. Navy Avatar asked Dec 21 '15 13:12

Carle B. Navy


1 Answers

It would require two loops.

    var arr = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
    //find the counts using reduce
    var cnts = arr.reduce( function (obj, val) {
        obj[val] = (obj[val] || 0) + 1;
        return obj;
    }, {} );
    //Use the keys of the object to get all the values of the array
    //and sort those keys by their counts
    var sorted = Object.keys(cnts).sort( function(a,b) {
        return cnts[b] - cnts[a];
    });
    console.log(sorted);
like image 169
epascarello Avatar answered Oct 19 '22 08:10

epascarello