如何将数组元素分组到新的组数组?

How to group array element to a new group array?

我有一组行:

   this.lines = [
    0: {indexLine: 0, group: 16, columns: [,…]}
    1: {indexLine: 1, group: 16,…}
    2: {indexLine: 2, group: 16,…}
    3: {indexLine: 3, group: 9,…}
    ]

我想按组对行进行分组,以便能够在不同的表格中呈现它。

我试过这个:

 let arr: any = {};
        this.lines.forEach((line) => {
          if (!arr[line.group]) {
            arr[line.group] = [];
          }

          arr[line.group].push(line);
        });

您可以使用 reduce 方法来获得您想要的:

const result = this.lines.reduce((acc, item) => {
  if (!acc[item.group]) {
    acc[item.group] = [];
  }
  acc[item.group].push(item);
  return acc;
}, {});

如果您想将所有组作为多个数组而不是一个对象来获取,您可以使用 Object.values 来做到这一点:

const groups = Object.values(result);

您可以使用 Set 从对象数组中获取唯一的 group 值。 new Set(lines.map(x => x.group) 将为您提供组的唯一值数组。

使用 Array.from().

将集合转换为数组

现在您可以使用 map 遍历唯一的组值,Array.filter 会为您提供所有匹配的元素。


let lines = [
    {indexLine: 0, group: 16},
    {indexLine: 1, group: 16},
    {indexLine: 2, group: 16},
    {indexLine: 3, group: 9},
];

const groupedLines = Array.from(new Set(lines.map(x=>x.group))).map(y => lines.filter(z => z.group === y));

console.log(groupedLines);

你可以使用lodash.groupBy

yarn add lodash.groupby(或npm install lodash.groupby --save

import groupBy from 'lodash.groupby'; // 12.6k (gzipped 4.8k)

// ...

console.log(groupBy(this.lines, ({group}) => group)));

( self-explanatory 那里的代码,每分钟 0 WTFs )