lodash sortBy then groupBy, is order maintained?

前端 未结 3 893
Happy的楠姐
Happy的楠姐 2021-02-14 10:56

I\'m having trouble figuring out from the lodash documentation if my assumption about sorting and grouping is correct.

If I use sortBy, then use groupBy, do the arrays p

3条回答
  •  隐瞒了意图╮
    2021-02-14 11:31

    The current implementation of _.groupBy is:

    // An internal function used for aggregate "group by" operations.
    var group = function(behavior) {
      return function(obj, iteratee, context) {
        var result = {};
        iteratee = cb(iteratee, context);
        _.each(obj, function(value, index) {
          var key = iteratee(value, index, obj);
          behavior(result, value, key);
        });
        return result;
      };
    };
    
    // Groups the object's values by a criterion. Pass either a string attribute
    // to group by, or a function that returns the criterion.
    _.groupBy = group(function(result, value, key) {
      if (_.has(result, key)) result[key].push(value); else result[key] = [value];
    });
    

    Basically it iterates through each of the items in the collection in order (if the collection is array-like, which it would be after a sortBy), and pushes them to an array based on their key value.

    So yes, I'm not sure if this is an "official" characteristic of _.groupBy, but it does preserve the order of array-like collections, and that's probably unlikely to change.

提交回复
热议问题