Skip to content

Instantly share code, notes, and snippets.

@Mds92
Last active March 1, 2019 14:25
Show Gist options
  • Save Mds92/053deeba7349ce59038d9980c5dba612 to your computer and use it in GitHub Desktop.
Save Mds92/053deeba7349ce59038d9980c5dba612 to your computer and use it in GitHub Desktop.
GroupBy an array in TypeScript
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