我正在尋找在TypeScript中創建數組擴展「排序」方法,其中數組可以由各種對象類型組成。我可以從任何組件調用這個擴展方法。TypeScript - 數組排序擴展方法
這種排序需要在一個對象屬性中進行排序(屬性可以是數字或字符串當然)和方向是枚舉類型(升序1或降序-1)。我有數組,我有sortDirection的枚舉。但是,我在哪裏/如何構建排序方法來像這樣調用它?
myArrayOfObjects.sort('name', sortDirection.Descending);
這裏是我現有的組件級排序,我試圖把它變成一個可以從任何地方調用的擴展方法。這是很容易把方向變成一個枚舉,並通過它,但我真的想使這是一個擴展方法:
sort(property: string): void {
this.isDescending = !this.isDescending;
this.column = property;
const direction = this.isDescending ? 1 : -1;
this.searchResults.sort(function (a, b) {
if (a[property] < b[property]) {
return -1 * direction;
} else if (a[property] > b[property]) {
return 1 * direction;
} else {
return 0;
}
});
this.currentPage = 0;
}
this.searchResults低於,但它可以是任何數組或任何物體與屬性。再次,這是目前的分量級函數,我想變成擴展方法用於數組:
@Input() searchResults: IPersonSummary[];
[在打字稿擴展陣列]的可能的複製(https://stackoverflow.com/questions/12802383/extending-array-in-typescript) – toskv