如何根据两个属性

时间:2018-05-25 14:06:27

标签: typescript

我想获得一组数组,如...... [[1,2],[5,8],[9]] ......取决于分组。

这是我从rxjs库示例中得到的示例。此ex仅使用一个属性进行分组。

Observable.of<Obj>({id: 1, age: 5, weight: 145},
                   {id: 9, age: 7, weight: 10},
                   {id: 2, age: 5, weight: 145},
                   {id: 60, age: 11, weight: 145},
    )
    .groupBy(p => p.id)
    .flatMap( (group$) => group$.reduce((acc, cur) => [...acc, cur], []))
    .subscribe(p => console.log(p));

预期结果:[[1,2],[9],[60]]

我没有设法让它适用于多个属性(年龄和体重)。

有人能告诉我如何实现这个目标吗?

谢谢,

2 个答案:

答案 0 :(得分:2)

您可以按功能为组指定更详细的功能并返回唯一键。例如年龄权重。我整理了一个jsfiddle https://jsfiddle.net/g5pj065m/3638/

Rx.Observable.of({id: 1, age: 5, weight: 145},
    {id: 9, age: 7, weight: 10},
    {id: 2, age: 5, weight: 145},
    {id: 60, age: 11, weight: 145}
)
.groupBy(p => {
    return `${p.age}- ${p.weight}`;
})
.flatMap( (group$) => group$.reduce((acc, cur) => [...acc, cur], []))
.subscribe(p => console.log(p));

答案 1 :(得分:0)

export interface GroupByModel {
    key: any;
    value: any[];
}

export class Utility {
  static groupBy(xs: any, f: Function): any[] {
    const groupByObjects = xs.reduce((r: any, v: any, i: any, a: any, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});
    const groupByModels: GroupByModel[] = [];
    for (const obj in groupByObjects) {
      if (!groupByObjects.hasOwnProperty(obj)) {
        continue;
      }
      groupByModels.push({
        key: obj,
        value: groupByObjects[obj]
      });
    }
    return groupByModels;
  }
}

使用:

console.log(Utility.groupBy(arrayToApplyGroupByOnIt, (a) => a.propertyNameToGroupByOnIt));

https://gist.github.com/Mds92/053deeba7349ce59038d9980c5dba612