typescript 根据打字稿中的属性对对象数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49048955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort array of objects based on property in typescript
提问by Willem de Jong
I'm showing an array with items of type 'request' in a table. I want to sort the columns of the table so I planned to make a click method for every column header. This methods sorts the array based on the value of the property shown in that column.
我在表格中显示了一个包含“请求”类型项目的数组。我想对表格的列进行排序,所以我计划为每个列标题制作一个 click 方法。此方法根据该列中显示的属性值对数组进行排序。
public sortProduct(): void {
this.requests.sort((a, b) => {
if (a.productName < b.productName)
return -1;
if (a.productName > b.productName)
return 1;
return 0;
});
if (!this.productSortOrder) {
this.requests.reverse();
this.productSortOrder = true;
} else {
this.productSortOrder = false;
}
}
This works, but now I need to make a method for every column. I am looking for a way to call a sort method like this:
这有效,但现在我需要为每一列制定一个方法。我正在寻找一种方法来调用这样的排序方法:
this.requests.sortMethod(property, order);
This method would then sort the requests array based on the property of the objects in the array and in the given sortorder. How can I do that? I guess I'm looking for something like Func<> in C#.
然后,此方法将根据数组中对象的属性和给定的排序顺序对请求数组进行排序。我怎样才能做到这一点?我想我在 C# 中寻找类似 Func<> 的东西。
回答by Titian Cernicova-Dragomir
You can us a function signature for a similar effect to Func
您可以使用函数签名来达到类似的效果 Func
sortProduct<T>(prop: (c: Product) => T, order: "ASC" | "DESC"): void {
this.requests.sort((a, b) => {
if (prop(a) < prop(b))
return -1;
if (prop(a) > prop(b))
return 1;
return 0;
});
if (order === "DESC") {
this.requests.reverse();
this.productSortOrder = true;
} else {
this.productSortOrder = false;
}
}
// Usage
sortProduct(p=> p.productName, "ASC");
Or you can use the property name instead (keyof Product
will ensure the string must be a property of Product
):
或者您可以改用属性名称(keyof Product
将确保字符串必须是 的属性Product
):
sortProduct<T>(propName: keyof Product, order: "ASC" | "DESC"): void {
this.requests.sort((a, b) => {
if (a[propName] < b[propName])
return -1;
if (a[propName] > b[propName])
return 1;
return 0;
});
...
}
// Usage
sortProduct("productName", "ASC");
sortProduct("productName_", "ASC"); // Error
回答by jerrybarolo
You can use a SortUtil class with a static template method sortByProperty:
您可以使用带有静态模板方法 sortByProperty 的 SortUtil 类:
export class SortUtil {
static sortByProperty<T>(array: T[], propName: keyof T, order: 'ASC' | 'DESC'): void {
array.sort((a, b) => {
if (a[propName] < b[propName]) {
return -1;
}
if (a[propName] > b[propName]) {
return 1;
}
return 0;
});
if (order === 'DESC') {
array.reverse();
}
}
}