【问题标题】:sorting an array where the second property may be nonexistent对第二个属性可能不存在的数组进行排序
【发布时间】:2018-08-28 21:51:06
【问题描述】:

我需要对 Angular 项目的表格进行排序。问题是,对于表中的某些值,我需要按数组中对象的直接属性进行排序,但对于其他值,我需要按该直接属性的子项进行排序。

例如,我将associate.lastname 用于一列,associate.client.name 用于另一列。我正在尝试用一种方法完成所有这些工作,并且我在 TypeScript 中有一个工作方法。

这是我的组件类中的sortBy 方法:

sortBy(option: SortOption, sortedBy: string) {
    const props = option.split('.');
    const parent = props[0];
    const child = props[1];
    const asc = this[sortedBy];
    if(!child) {
        this.associates.sort((associateA, associateB)=> {
            if (associateA[parent] < associateB[parent]) {
                return asc === true ? -1 : 1;
            } else if (associateB[parent] < associateA[parent]) {
                return asc === true ? 1 : -1;
            } else {
                return 0;
            }
        });
    } else {
        this.associates.sort((associateA, associateB)=> {
            if (associateA[parent][child] < associateB[parent][child]) {
                return asc === true ? -1 : 1;
            } else if (associateB[parent][child] < associateA[parent][child]) {
                return asc === true ? 1 : -1;
            } else {
                return 0;
            }
        });
      }
      this[sortedBy] = !this[sortedBy]
}

SortOption 是一个枚举,其值中可能有也可能没有.。我在那段时间拆分得到父子属性,然后根据父子是否存在对数组进行排序。

现在我想知道是否有更好、更干燥的方法来做到这一点。您会注意到 if 和 else 语句中的代码几乎完全相同,除了是否使用了 child 属性,但我想不出更简洁的方法来做到这一点。

有没有更好的办法?

【问题讨论】:

    标签: arrays angular typescript object


    【解决方案1】:

    你可能想提取一个排序键函数:

    let sortingKey: (associate: any) => number;  // or some other type, depends on your code
    if (child) {
        sortingKey = (associate) => associate[parent][child];
    } else {
        sortingKey = (associate) => associate[parent];
    }
    

    之后你就可以简单地写了:

    this.associates.sort((associateA, associateB)=> {
        if (sortingKey(associateA) < sortingKey(associateB)) {
            return asc === true ? -1 : 1;
        } else if (sortingKey(associateB) < sortingKey(associateA)) {
            return asc === true ? 1 : -1;
        } else {
            return 0;
        }
    });
    

    【讨论】:

    • 完美。正在殴打自己,试图找到一种将其分解为函数的方法,但没有看到它。谢谢。
    猜你喜欢
    • 2022-12-11
    • 2011-10-25
    • 1970-01-01
    • 2020-11-19
    • 2020-09-22
    • 2016-11-05
    • 2015-05-06
    • 2021-11-01
    相关资源
    最近更新 更多