Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
sortedGroupBy using Underscore

sortedGroupBy

jsFiddle Example

Convenience function for performing a groupBy on a list then a sortBy on the resulting groups using Underscore methods.

sortedGroupBy(list, groupByIterator, sortByIterator)
sortedGroupBy = (list, groupByIter, sortByIter) ->
# Pass in an array to group by multiple object keys
if _.isArray(groupByIter)
groupBy = (obj) ->
_.map groupByIter, (key, value) -> obj[key]
else
groupBy = groupByIter
# Pass in an array to sort by multiple object keys
if _.isArray(sortByIter)
sortBy = (obj) ->
_.map sortByIter, (key, value) -> obj[key]
else
sortBy = sortByIter
groups = _.groupBy(list, groupBy)
_.each groups, (value, key, list) ->
list[key] = _.sortBy(value, sortBy)
return groups
function sortedGroupBy(list, groupByIter, sortByIter) {
if (_.isArray(groupByIter)) {
function groupBy(obj) {
return _.map(groupByIter, function(key, value) {
return obj[key];
});
}
} else {
var groupBy = groupByIter;
}
if (_.isArray(sortByIter)) {
function sortBy(obj) {
return _.map(sortByIter, function(key, value) {
return obj[key];
});
}
} else {
var sortBy = sortByIter;
}
var groups = _.groupBy(list, groupBy);
_.each(groups, function(value, key, list) {
list[key] = _.sortBy(value, sortBy);
});
return groups;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment