Skip to content

Instantly share code, notes, and snippets.

@sankarseran
Created March 2, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sankarseran/d7fec3660117f04353c3ad9f30edd6ce to your computer and use it in GitHub Desktop.
Save sankarseran/d7fec3660117f04353c3ad9f30edd6ce to your computer and use it in GitHub Desktop.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(collection: Array, property: string): Array {
// prevents the application from breaking if the array of objects doesn't exist yet
if(!collection) {
return null;
}
const groupedCollection = collection.reduce((previous, current)=> {
if(!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
// this will return an array of objects, each object containing a group of objects
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment