Count and sort by number of occurrences
I have an array like this:
var items = [
{name: 'popcorn', category: 'snacks'},
{name: 'nachos', category: 'snacks'},
...
{name: 'coke', category: 'drinks'}
];
I want to get a list of categories ordered by the number of items on it
(most items first):
['snacks', 'drinks']
Here is how I did it:
var categories = _.chain(items)
.countBy(function (i) { return i.category })
.pairs()
.sortBy(function (c) { return -c[1] })
.value();
So the result of countBy is an object, and I have to use pairs to convert
it into an array of arrays in order to sort it.
I wonder if there is a more straightforward way to do it? Built-in function?
No comments:
Post a Comment