lodash sortBy然后groupBy,订单是否得到维护? [英] lodash sortBy then groupBy, is order maintained?

查看:99
本文介绍了lodash sortBy然后groupBy,订单是否得到维护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我对排序和分组的假设是正确的,我将无法从lodash文档中找出答案.

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

如果我使用sortBy,然后使用groupBy,由groupBy生成的数组是否保持项目的排序顺序?

If I use sortBy, then use groupBy, do the arrays produced by groupBy maintain the sort order of items?

例如,说我有以下数组:

For example, say I have the following array:

var testArray = [[5,6],[1,3],[5,4],[5,1]]

我想按它们的第一个元素对它们进行分组,但还要让它们按这些组中的第二个元素进行排序.因此,在lodash中,我假设我可以执行以下操作:

And I would like to group these by their first element, but also have them sorted by their second element within these groups. So, in lodash I assume I can do the following:

_.chain(testArray)
  .sortBy(function (item) { return item[1]; })
  .groupBy(function (item) { return item[0]; })
  .value()

最终会产生我期望的结果:

Which ends up producing what I would expect it to:

{
  1: [[1,3]]
  5: [[5,1],[5,4],[5,6]]
}

这只是巧合吗?关于so​​rtBy和groupBy如何工作以确保分组数组的这种排序有什么关系吗?该文档说sortBy是一种稳定的排序,是否以同样的方式适用于groupBy?有什么理由让我不认为这每次都会起作用吗?

Is this just coincidence? Is there anything about how sortBy and groupBy work that ensures this ordering of the grouped arrays? The documentation says that sortBy is a stable sort, does that in the same way apply to groupBy? Is there any reason I should not assume this will work every time?

推荐答案

_.groupBy的当前实现是:

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];
});

基本上按顺序迭代集合中的每个项目(如果集合是数组形式的(在sortBy之后),然后根据其键值将它们推入数组.

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.

是的,我不确定这是否是_.groupBy的官方"特征,但是它确实保留了类似数组的集合的顺序,并且可能不太可能改变.

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.

这篇关于lodash sortBy然后groupBy,订单是否得到维护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆