TypeScript按对象排序数组

时间:2016-09-06 12:00:38

标签: arrays typescript

有没有人知道如何在任务中按值TaskTime对Person进行排序?

export class Person {
    Id: string;
    Email: string;
    FirstName: string;
    LastName: string;
    Presence: boolean;
    RegisterTime: Date;
    tasks: Array<Task>
}

export class Task {
    TaskName: string;
    DoneTask: boolean;
    TaskTime: number;
}

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

javascript Array对象附带内置sort method,你传递一个比较函数,如下所示:

function compare(a, b) {
    if (a is less than b by some ordering criterion) {
        return -1;
    }

    if (a is greater than b by the ordering criterion) {
        return 1;
    }

    // a must be equal to b
    return 0;
}

所以在你的情况下:

let person = new Person();
console.log(person.tasks.sort((task1, task2) => task1.TaskTime - task2.TaskTime));

答案 1 :(得分:3)

尝试按照这种方式对数组进行排序。下面的示例代码将按blockId字段按降序对数组进行排序。

this.itemList.sort((left, right): number => {
  if (left.blockId < right.blockId) return 1;
  if (left.blockId > right.blockId) return -1;
  return 0;
});