From 96fdf6fbac96b47c127c5908c96d3c1e640a31ad Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Fri, 21 Oct 2011 14:44:38 -0400 Subject: [PATCH] Adding the ability to _.groupBy(list, 'account_id') --- test/collections.js | 6 ++++++ underscore.js | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/test/collections.js b/test/collections.js index cf1c815d6..009d2f327 100644 --- a/test/collections.js +++ b/test/collections.js @@ -202,6 +202,12 @@ $(document).ready(function() { var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; }); ok('0' in parity && '1' in parity, 'created a group for each value'); equals(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group'); + + var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]; + var grouped = _.groupBy(list, 'length'); + equals(grouped['3'].join(' '), 'one two six ten'); + equals(grouped['4'].join(' '), 'four five nine'); + equals(grouped['5'].join(' '), 'three seven eight'); }); test('collections: sortedIndex', function() { diff --git a/underscore.js b/underscore.js index a50ac4b81..16b076276 100644 --- a/underscore.js +++ b/underscore.js @@ -276,9 +276,11 @@ }), 'value'); }; - // Groups the object's values by a criterion produced by an iterator - _.groupBy = function(obj, iterator) { + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = function(obj, val) { var result = {}; + var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; each(obj, function(value, index) { var key = iterator(value, index); (result[key] || (result[key] = [])).push(value);