How to group data in Angular 2?
I would create a custom pipe to do that as described below:
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(value: Array<any>, field: string): Array<any> {
const groupedObj = value.reduce((prev, cur)=> {
(prev[cur[field]] = prev[cur[field]] || []).push(cur);
return prev;
}, {});
return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
}
}
And then on your template you can write:
<div *ngFor="let item of employees | groupBy: 'department'">
Department {{ item.key }} has {{ item.value.length }} employees
</div>
See also corresponding plunker https://plnkr.co/edit/49fWY1rMbSZtNQ3H