Dennis February 2016

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

Answers


Martin Vseticka February 2016

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

Post Status

Asked in February 2016
Viewed 3,851 times
Voted 11
Answered 1 times

Search




Leave an answer