Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Sort Object by Object in Array

Does anyone know how sort Array with Person by value TaskTime in tasks?

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;
}

Thanks for help

like image 739
James Avatar asked Sep 23 '26 09:09

James


1 Answers

The javascript Array object comes with a builtin sort method, you pass it a compare function like this:

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;
}

So in your case:

let person = new Person();
console.log(person.tasks.sort((task1, task2) => task1.TaskTime - task2.TaskTime));
like image 194
Nitzan Tomer Avatar answered Sep 26 '26 01:09

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!