我正在寻找在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