Created
March 5, 2020 22:13
-
-
Save Disane87/87d3a301f9c8252316e0221c3f253e38 to your computer and use it in GitHub Desktop.
Array orderBy by properties in array type
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
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