Search code examples
angularangular5angular2-ngfor

How can i iterate over array of objects and change group label when its different than last one?


i have an array of objects that looks like this:

[
  {group_label: Colors, label: Red, value: '1'},
  {group_label: Colors, label: Green, value: '2'},
  {group_label: Sizes, label: S, value: '3'},
  {group_label: Sizes, label: M, value: '4'},
  {group_label: Sizes, label: L, value: '5'}
]

and i want to iterate over it with *ngFor and get this result:

Colors:
  Red: 1
  Green: 2
Sizes:
  S: 3
  M: 4
  L: 5

and my problem is, how do i show group_label only once at start of each "section". I cant reformat those objects to something more appropriate to this task as they are Angulars FormGroup in FormArrays.


Solution

  • You can create a pipe to group these:

    @Pipe({name: 'group'})
    export class GroupPipe implements PipeTransform {
      transform(values: Array<any>): Array<any> {
        // {group_label: Colors, label: Red, value: '1'}
        const groups = values.reduce((all, row) => {
          all[row.group_label] = all[row.group_label] || []; 
          all[row.group_label].push(row);
        }, {});
        return Object.keys(groups).map(group => ({ group_label: group, labels: groups[group]}));
      }
    }
    

    Now use nested ngFor:

    <div *ngFor="let group of (unsortedGroups | group)">
      {{ group.group_label }}
      <div *ngFor="let label of group.labels">
        {{ label.label }}: {{ label.value }}
      </div>
    </div>