关于angular:lodash-使用_.groupBy创建数组之前对其进行排序

lodash - sort result of _.groupBy before creating an array with it

我正在使用lodash的groupBy按1到10的数字值对对象进行分组。让我们将属性称为" sort"

groupBy的结果看起来像

1
2
3
4
5
{
    1:[{sort:1,...}, ...],
    2:[{sort:2,...}], ...].
    ...
}

接下来,我使用Object.values(result)将其转换回二维数组,以双ngFor角度显示。

问题是我不能确定(可以吗?)对象的顺序是否正确。 groupBy是否以最适合的顺序创建密钥?

所以如果结果看起来像

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

在将_groupBy结果推入数组之前如何对其进行预排序?


由于您的键是数字,因此Object.values()将创建一个数组,其值按原始键的数字值排序。

1
2
3
4
5
6
7
8
9
const data = {
    3:3,
    1:1,
    2:2,
};

const result = Object.values(data);

console.log(result);


_.groupBy方法的文档中对此进行了非常明确的定义:

Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).

如果您想订购这些,则需要在_.groupBy之前先_.orderBy / _.sortBy


我也很难信任JavaScript对象的迭代顺序。 我建议您通过使用lodash的sortBy函数来消除不确定性。

如果我正确地解释了您的问题,则将sortBy应用于result对象(使用_.property iteratee速记)应该会为您提供要寻找的2D数组结构:

1
this.target_data = _.sortyBy(result, 'sort');

this.target_data变成2D数组:第一行是sort = 1的对象列表,下一行是sort = 2的对象列表,依此类推。

请查看此快速演示。