Group By multiple columns in Angular 4

Viewed 2794

I am trying to group by array in angular 4. I am using the custom pipe approach to group by the array as found in:

https://www.competa.com/blog/custom-groupby-pipe-angular-4/

But I am trying to group by multiple columns.

Data

var myArray = [
    {
        name: "Apple",
        color: "Green",
        grade: "A1"
    },
    {
        name: "Apple",
        color: "Red",
        grade: "A1"
    },
    {
        name: "Apple",
        color: "Green",
        grade: "A2"
    },
    {
        name: "Apple",
        color: "Red",
        grade: "A2"
    },
];

Here I want to group by multiple columns say, name and Grade.

I have tried using like this with no help:

<li *ngFor="let object of myArray | groupBy:'name,grade'"></li>

Please provide your valuable solutions to resolve this issue. Appreciate your help. Thanks.

2 Answers

you can group your array in the component using reduce function :

groups = Object.values(this.myArray.reduce(function(r, e) {
      var key = e.name + '|' + e.grade;
      if (!r[key]) r[key] = e;
      else {
        r[key].color = e.color;
      }
      return r;
}, {}));

https://jsfiddle.net/ov4nx7ad/

From my end best way is to use lodash.

HTML:-

<ul>
    <li *ngFor="let object of myArray | groupBy:['color','name']"></li>
</ul>

Pipe:-

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';

@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
    transform(collection: Array, property: Array): Array {

        if(!collection) {
            return null;
        }
        var notNull = _.negate(_.isNull);
        const groupedCollection = _.groupBy(collection, function(note){
                          return _.find(_.pick(note, property), notNull);
        });
        return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
    }
}
Related