Using Underscore.js, I\'m trying to group a list of items multiple times, ie
Group by SIZE then for each SIZE, group by CATEGORY...
http://jsfiddle.net/ricky
I think @Bergi's answer can be streamlined a bit by utilizing Lo-Dash's mapValues
(for mapping functions over object values). It allows us to group the entries in an array by multiple keys in a nested fashion:
_ = require('lodash');
var _.nest = function (collection, keys) {
if (!keys.length) {
return collection;
}
else {
return _(collection).groupBy(keys[0]).mapValues(function(values) {
return nest(values, keys.slice(1));
}).value();
}
};
I renamed the method to nest
because it ends up serving much the same role served by D3's nest operator. See this gist for details and this fiddle for demonstrated usage with your example.
lodash nest groupby