Skip to content

Instantly share code, notes, and snippets.

@sirmews
Forked from guillaumegarcia13/groupBy.ts
Created May 22, 2019 03:55
Show Gist options
  • Save sirmews/34a9bcc0b46a155e07d44ebd08cfeac9 to your computer and use it in GitHub Desktop.
Save sirmews/34a9bcc0b46a155e07d44ebd08cfeac9 to your computer and use it in GitHub Desktop.
groupBy in Typescript (for use in Angular)
declare global {
interface Array<T> {
groupBy(prop: T): Array<T>;
}
}
if (!Array.prototype.groupBy) {
Array.prototype.groupBy = (prop: string) => {
return this.reduce(function(groups, item) {
const val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment