24

使用 Underscore.js,我试图多次对项目列表进行分组,即

按 SIZE 分组,然后为每个 SIZE,按 CATEGORY 分组...

http://jsfiddle.net/rickysullivan/WTtXP/1/

理想情况下,我想要一个函数或扩展_.groupBy(),以便您可以将一个数组与参数一起扔给它以进行分组。

var multiGroup = ['size', 'category'];

应该可以做个mixin吧……

_.mixin({
    groupByMulti: function(obj, val, arr) {
        var result = {};
        var iterator = typeof val == 'function' ? val : function(obj) {
                return obj[val];
            };
        _.each(arr, function(arrvalue, arrIndex) {
            _.each(obj, function(value, objIndex) {
                var key = iterator(value, objIndex);
                var arrresults = obj[objIndex][arrvalue];
                if (_.has(value, arrvalue))
                    (result[arrIndex] || (result[arrIndex] = [])).push(value);

我的头很痛,但我认为这里需要更多的推动......

            });
        })
        return result;
    }
});

properties = _.groupByMulti(properties, function(item) {

    var testVal = item["size"];

    if (parseFloat(testVal)) {
        testVal = parseFloat(item["size"])
    }

    return testVal

}, multiGroup);
4

9 回答 9

41

一个简单的递归实现:

_.mixin({
  /*
   * @mixin
   *
   * Splits a collection into sets, grouped by the result of running each value
   * through iteratee. If iteratee is a string instead of a function, groups by
   * the property named by iteratee on each of the values.
   *
   * @param {array|object} list - The collection to iterate over.
   * @param {(string|function)[]} values - The iteratees to transform keys.
   * @param {object=} context - The values are bound to the context object.
   * 
   * @returns {Object} - Returns the composed aggregate object.
   */
  groupByMulti: function(list, values, context) {
    if (!values.length) {
      return list;
    }
    var byFirst = _.groupBy(list, values[0], context),
        rest    = values.slice(1);
    for (var prop in byFirst) {
      byFirst[prop] = _.groupByMulti(byFirst[prop], rest, context);
    }
    return byFirst;
  }
});

在你的 jsfiddle 中演示

于 2012-12-13T21:48:50.577 回答
17

我认为@Bergi 的答案可以通过利用 Lo-Dash mapValues (用于将函数映射到对象值)来简化一点。它允许我们以嵌套方式通过多个键对数组中的条目进行分组:

_ = 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();
  }
};

我将该方法重命名为,nest因为它最终服务于 D3 的嵌套操作员所服务的角色。有关详细信息,请参阅此要点,有关您的示例的演示用法,请参阅此小提琴

于 2014-03-28T15:27:47.370 回答
16

这个相当简单的hack怎么样?

console.log(_.groupBy(getProperties(), function(record){
    return (record.size+record.category);
}));
于 2013-08-22T18:48:39.177 回答
1

查看这个下划线扩展:Underscore.Nest,由 Irene Ros 编写。

这个扩展的输出会和你指定的略有不同,但是这个模块只有大约 100 行代码,所以你应该可以扫描得到方向。

于 2012-12-13T21:15:54.973 回答
0

这是map-reduce的reduce阶段的一个很好的用例。它不会像多组功能那样在视觉上优雅(您不能只传递一组键来进行分组),但总体而言,这种模式为您提供了转换数据的更大灵活性。例子

var grouped = _.reduce(
    properties, 
    function(buckets, property) {
        // Find the correct bucket for the property
        var bucket = _.findWhere(buckets, {size: property.size, category: property.category});

        // Create a new bucket if needed.
        if (!bucket) {
            bucket = {
                size: property.size, 
                category: property.category, 
                items: []
            };
            buckets.push(bucket);
        }

        // Add the property to the correct bucket
        bucket.items.push(property);
        return buckets;
    }, 
    [] // The starting buckets
);

console.log(grouped)

但是,如果您只想将它​​放在下划线 mixin 中,这是我的尝试:

_.mixin({
'groupAndSort': function (items, sortList) {
    var grouped = _.reduce(
        items,
        function (buckets, item) {
            var searchCriteria = {};
            _.each(sortList, function (searchProperty) { searchCriteria[searchProperty] = item[searchProperty]; });
            var bucket = _.findWhere(buckets, searchCriteria);

            if (!bucket) {
                bucket = {};
                _.each(sortList, function (property) { bucket[property] = item[property]; });
                bucket._items = [];
                buckets.push(bucket);
            }

            bucket._items.push(item);
            return buckets;
        },
        [] // Initial buckets
    );

    grouped.sort(function (x, y) {
        for (var i in sortList) {
            var property = sortList[i];
            if (x[property] != y[property])
                return x[property] > y[property] ? 1 : -1;
        }
        return 0;
    });

    return _.map(grouped, function (group) {
        var toReturn = { key: {}, value: group.__items };
        _.each(sortList, function (searchProperty) { toReturn.key[searchProperty] = group[searchProperty]; });
        return toReturn;
    });
});
于 2013-11-12T23:36:59.257 回答
0

Joyrexus 对 bergi 方法的改进没有利用下划线/lodash 混合系统。这是一个混合:

_.mixin({
  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();
    }
  }
});
于 2015-05-07T02:21:40.243 回答
0

一个 lodash 和 mixin 的例子

_.mixin({
'groupByMulti': function (collection, keys) {
if (!keys.length) {
 return collection;
 } else {
  return _.mapValues(_.groupBy(collection,_.first(keys)),function(values) {
    return _.groupByMulti(values, _.rest(keys));
  });
}
}
});    
于 2015-07-17T12:09:02.990 回答
0

这是一个易于理解的功能。

function mixin(list, properties){

    function grouper(i, list){

        if(i < properties.length){
            var group = _.groupBy(list, function(item){
                var value = item[properties[i]];
                delete item[properties[i]];
                return value;
            });

            _.keys(group).forEach(function(key){
                group[key] = grouper(i+1, group[key]);
            });
            return group;
        }else{
            return list;
        }
    }

    return grouper(0, list);

}
于 2016-08-29T18:51:15.580 回答
0

在大多数情况下,按复合键分组对我来说效果更好:

const groups = _.groupByComposite(myList, ['size', 'category']);

使用 OP 的小提琴演示

米信

_.mixin({
  /*
   * @groupByComposite
   *
   * Groups an array of objects by multiple properties. Uses _.groupBy under the covers,
   * to group by a composite key, generated from the list of provided keys.
   *
   * @param {Object[]} collection - the array of objects.
   * @param {string[]} keys - one or more property names to group by.
   * @param {string} [delimiter=-] - a delimiter used in the creation of the composite key.
   *
   * @returns {Object} - the composed aggregate object.
   */
  groupByComposite: (collection, keys, delimiter = '-') =>
    _.groupBy(collection, (item) => {
      const compositeKey = [];
      _.each(keys, key => compositeKey.push(item[key]));
      return compositeKey.join(delimiter);
    }),
});
于 2017-11-01T18:34:31.397 回答