5

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;
});
1
  • Have you solved your issue? Commented Feb 9, 2016 at 6:51

2 Answers 2

6

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Can you explain your answer?
It's quite simple, 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.
Please add this explanation to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.