Adding groupBy.

This commit is contained in:
Andrei
2011-05-05 14:00:40 -04:00
parent c174663ea3
commit f8a4b78a86
3 changed files with 33 additions and 1 deletions

View File

@@ -250,6 +250,21 @@
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion produced by an iterator
_.groupBy = function(obj, iterator) {
var result = {};
each(obj, function(value) {
var key = iterator(value);
if (result.hasOwnProperty(key)) {
result[key].push(value);
}
else {
result[key] = [value];
}
});
return result;
}
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.