Dennis
Dennis

Reputation: 1848

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

Upvotes: 5

Views: 9825

Answers (2)

Eber
Eber

Reputation: 179

Something like this should work. The method compares the current and next values and adds comparison to the case when the two age values are the same. Then assume the column name in order based on age.

private compareTo(val1, val2, typeField) {
    let result = 0;
    if (typeField == "ftDate") {
        result = val1 - val2;
    } else {
        if (val1 < val2) {
            result = - 1;
        } else if (val1 > val2) {
            result = 1;
        } else {
            result = 0;
        }
    }

    return result;
}

-

this.model.mylist.sort((a, b) => {
    let cols = ["age", "name"];

    let i = 0, result = 0, resultordem = 0;

    while (result === 0 && i < cols.length) {
        let col = cols[i];
        let valcol1 = a[col];
        let valcol2 = b[col];
        let typeField = "string";

        if (col == "age") {
            typeField = "number";
        }

        if (valcol1 != "null" && valcol1 != "null") {
            resultordem = this.compareTo(valcol1, valcol2, typeField);

            if (resultordem != 0) {
                break;
            }
        }
        i++;
    }
    return resultordem;
});

Upvotes: 0

MartyIX
MartyIX

Reputation: 28648

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

Upvotes: 6

Related Questions