首页 > 解决方案 > 在打字稿中对不同的数组进行排序

问题描述

我正在尝试对我的打字稿模型中的一些参数进行排序。我的模型如下。

export class DataModel {
   ID: String
   point1: Point
   point2 : Point
   point3: Point
   AnotherPoint1: AnotherPoint[]
   AnotherPoint2: AnotherPoint[]
   AnotherPoint3: AnotherPoint[]
}

export class Point {
 Name: String
 Timestamp: String
}

export class AnotherPoint {
 Name: String
 Timestamp: String
}

我的组件中有排序逻辑,它采用上述数据模型并将点排序如下:

     private sortByNameAndID(dataModel: DataModel[]): DataModel[] {
        return dataModel.sort(function (a, b) {
          const pointA = a.point1.Name.toLowerCase();
          const pointB = b.point1.Name.toLowerCase();
          if (pointA === pointB) {
            const timeA = a.point1.Timestamp;
            const timeB = b.point1.Timestamp;
  return Service.compareDate(new Date(timeA), new Date(timeB));  //here again comparing dates
          }
          if (pointA < pointB ) {
            return -1;
          }
          if (pointA > pointB ) {
            return 1;
          }
        });
      }
    }

上面的排序逻辑对 Points 工作正常,但现在我还需要对 AnotherPoint 进行排序。意味着我必须如上所述将所有 Points 和 AnotherPoints 排序在一起。我怎样才能做到这一点?

标签: javascriptangulartypescriptangular8

解决方案


我将开始创建两个辅助函数,分别比较两个Points 和两个 s 数组AnotherPoint。我假设数组将逐个元素进行比较,一旦一对元素不与 0 比较就停止。

function comparePoints(pA: Point | AnotherPoint, pB: Point | AnotherPoint)
{
    const pointA = pA.Name.toLowerCase();
    const pointB = pB.Name.toLowerCase();
    if (pointA < pointB ) {
        return -1;
    }
    if (pointA > pointB ) {
        return 1;
    }
    const timeA = pA.Timestamp;
    const timeB = pB.Timestamp;
    return Service.compareDate(new Date(timeA), new Date(timeB));
}

function comparePointArrays(arrayA: AnotherPoint[], arrayB: AnotherPoint[])
{
    const len = Math.min(arrayA.length, arrayB.length);
    for (let i = 0; i < len; ++i)
    {
        const result = comparePoints(arrayA[i], arrayB[i]);
        if (result !== 0) {
            return result;
        }
    }
    return 0;
}

然后可以使用新的辅助比较器重写排序函数:

private sortByNameAndID(dataModel: DataModel[]): DataModel[] {
    return dataModel.sort(function (a, b) {
        return comparePoints(a.point1, b.point1) ||
            comparePoints(a.point2, b.point2) ||
            comparePoints(a.point3, b.point3) ||
            comparePointArrays(a.AnotherPoint1, b.AnotherPoint1) ||
            comparePointArrays(a.AnotherPoint2, b.AnotherPoint2) ||
            comparePointArrays(a.AnotherPoint3, b.AnotherPoint3);
    });
}

请注意,如果左侧运算的结果为falsy|| (0),则运算符仅执行右侧运算,这意味着一旦比较报告非零结果,我们将停止比较点。


推荐阅读