Skip to content

Instantly share code, notes, and snippets.

@debbbbie
Forked from bruth/README.md
Last active August 29, 2015 14:21
Show Gist options
  • Save debbbbie/88ff80f91b00b46263b3 to your computer and use it in GitHub Desktop.
Save debbbbie/88ff80f91b00b46263b3 to your computer and use it in GitHub Desktop.

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