Created
March 2, 2019 13:52
-
-
Save sankarseran/d7fec3660117f04353c3ad9f30edd6ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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