在TypeScript中按属性对对象数组进行排序

5

我正在表格中展示一组类型为“请求”的数组。我想对表格的列进行排序,所以计划为每个列标题创建一个点击方法。这些方法会根据该列中显示的属性值对数组进行排序。

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.requests.sortMethod(property, order);

此方法将基于数组中对象的属性和给定的排序顺序对请求数组进行排序。 我该怎么做?我猜我正在寻找类似于C#中的Func<>的东西。
2个回答

11
您可以使用函数签名来实现类似于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");

或者您可以使用属性名称(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

谢谢,我已经让它工作了,但是我不理解“函数签名”。我省略了函数这个词并将其添加到我的类中。现在对它的调用将是 this.sortProduct(p=> p.productName, "ASC"); - Willem de Jong
1
一个函数签名与 Func 相同,上面的签名将与 Func<Product, T> 相同(我假设您具有 C# 背景,并且这对您有意义)。语法为 (paramList) => returnType,其中 paramListparam1: pramType1, param2: pramType2,... - Titian Cernicova-Dragomir

5
您可以使用SortUtil类的静态模板方法sortByProperty:
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();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接