根据打字稿中的属性对对象数组进行排序

Wil*_*ong 2 sorting typescript

我在表中显示一个数组,其中包含“请求”类型的项。我想对表的列进行排序,所以我计划为每个列标题创建一个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;
    }        
}   
Run Code Online (Sandbox Code Playgroud)

这行得通,但是现在我需要为每列创建一个方法。我正在寻找一种调用像这样的排序方法的方法:

this.requests.sortMethod(property, order);
Run Code Online (Sandbox Code Playgroud)

然后,此方法将根据数组中对象的属性以及给定的排序顺序对请求数组进行排序。我怎样才能做到这一点?我想我正在C#中寻找像Func <>这样的东西。

Tit*_*mir 6

您可以使用函数签名来获得与 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");
Run Code Online (Sandbox Code Playgroud)

或者,您可以改用属性名称(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
Run Code Online (Sandbox Code Playgroud)


jer*_*olo 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)