Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript sorting array with objects on multiple properties

I like to sort an array with objects that have multiple properties. My objects have a string called name and a boolean called mandatory.

First i want to sort on age, next on the name.

How do I do this?

Ordering by age is easy...:

this.model.mylist.sort((obj1: IObj, obj2: IObj => {
    if (obj1.age < obj2.age) {
        return -1;
    }
    if (obj1.age > obj2.age) {
        return 1;
    }
    return 0;
});
like image 504
Dennis Avatar asked Feb 08 '16 11:02

Dennis


1 Answers

Well, you only add comparation for case when the two age values are the same. So something like this should work:

this.model.mylist.sort((obj1: IObj, obj2: IObj) => {
    if (obj1.age < obj2.age) {
        return -1;
    }
    if (obj1.age > obj2.age) {
        return 1;
    }

    return obj1.name.localeCompare(obj2.name);
});
like image 184
Martin Vseticka Avatar answered Oct 20 '22 18:10

Martin Vseticka