Last active
March 1, 2019 14:25
-
-
Save Mds92/053deeba7349ce59038d9980c5dba612 to your computer and use it in GitHub Desktop.
GroupBy an array in TypeScript
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
export interface GroupByModel { | |
key: any; | |
value: any[]; | |
} | |
export class Utility { | |
static groupBy(xs: any, f: Function): any[] { | |
const groupByObjects = xs.reduce((r: any, v: any, i: any, a: any, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {}); | |
const groupByModels: GroupByModel[] = []; | |
for (const obj in groupByObjects) { | |
if (!groupByObjects.hasOwnProperty(obj)) { | |
continue; | |
} | |
groupByModels.push({ | |
key: obj, | |
value: groupByObjects[obj] | |
}); | |
} | |
return groupByModels; | |
} | |
} | |
// Using: | |
// Utility.groupBy(arrayToApplyGroupByOnIt, (a) => a.propertyNameToGroupByOnIt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment