【问题标题】:Sort array of objects based on property in typescript根据打字稿中的属性对对象数组进行排序
【发布时间】:2018-03-01 11:40:28
【问题描述】:

我在表格中显示了一个包含“请求”类型项目的数组。我想对表格的列进行排序,所以我计划为每个列标题创建一个单击方法。此方法根据该列中显示的属性值对数组进行排序。

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 的东西。

【问题讨论】:

    标签: sorting typescript


    【解决方案1】:

    您可以使用函数签名来实现与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");
    • 函数签名与Func 相同,上述签名与Func&lt;Product, T&gt; 相同(我假设您有C# 背景,这对您来说很有意义)。语法为(paramList) =&gt; returnType,其中paramListparam1: pramType1, param2: pramType2,...
    【解决方案2】:

    您可以使用带有静态模板方法 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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 2018-10-09
      • 1970-01-01
      • 2017-02-12
      • 2023-02-03
      • 2015-06-17
      • 2019-02-11
      • 2017-02-23
      相关资源
      最近更新 更多