Skip to content

Instantly share code, notes, and snippets.

@Disane87
Created March 5, 2020 22:13
Show Gist options
  • Save Disane87/87d3a301f9c8252316e0221c3f253e38 to your computer and use it in GitHub Desktop.
Save Disane87/87d3a301f9c8252316e0221c3f253e38 to your computer and use it in GitHub Desktop.
Array orderBy by properties in array type
type FlattenIfArray<T> = T extends (infer R)[] ? R : T;
interface Array<T> {
orderBy<K extends keyof FlattenIfArray<T>>(key: K): Array<any>;
}
Array.prototype.orderBy = function<K>(key: K): Array<any> {
return this.sort((a: any, b: any) => a[key] - b[key]);
}
interface Test {
test1: string
}
let array: Array<Test> = [{test1: '14'},{test1: '3'}, {test1: '97'}, {test1: '1'}];
console.table(array);
console.table(array.orderBy('test1'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment