在打字稿中对不同的数组进行排序

Sorting different arrays in typescript

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

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 排序在一起。我该怎么做?

我将开始创建两个辅助函数,分别比较两个 Point 和两个 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)时才执行右边的运算,这意味着我们将一旦比较报告非零结果,就停止比较点。