Underscore.js groupBy multiple values

前端 未结 9 1444
渐次进展
渐次进展 2020-12-01 05:03

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

9条回答
  •  一整个雨季
    2020-12-01 05:16

    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

提交回复
热议问题