Last active
December 3, 2020 06:05
-
-
Save Pogix3m/c9e39c9829e6d810dfbdcceb5d4d640e to your computer and use it in GitHub Desktop.
Group Array By Id in TypeScript
This file contains hidden or 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
/* tslint:disable */ | |
export {}; | |
type TGroup<T> = {Id: any; Values: T[]}; | |
declare global { | |
interface Array<T> { | |
groupBy(aKey: string): TGroup<T>[]; | |
} | |
} | |
Array.prototype.groupBy = function<T>(aKey: string): TGroup<T>[] | |
{ | |
const lReducer: any = (lPrevious: TGroup<T>[], lCurrentValue: T) => | |
{ | |
const lExisting: TGroup<T> | undefined | |
= lPrevious.find((aValue: TGroup<T>) => aValue.Id === lCurrentValue[aKey]); | |
if (lExisting) | |
{ | |
lExisting.Values.push(lCurrentValue); | |
} | |
else | |
{ | |
lPrevious.push( | |
{ | |
Id: lCurrentValue[aKey], | |
Values: [lCurrentValue], | |
}); | |
} | |
return lPrevious; | |
}; | |
return this.reduce(lReducer, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
require("./Array.extension.ts") --> Use correct path to load on your start up file
Result: