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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With