0

I've been reading similar posts all day but can't figure out how to sort my javascript array by multiple properties. My array has a 'name' and 'type' property. To sort by name I now use:

                byNameDesc.sort(function (a, b) {
                    var x = a.name.toLowerCase();
                    var y = b.name.toLowerCase();
                    return y < x ? -1 : y > x ? 1 : 0;
                });

Works great. I want to enhance this function. If 'name' is 'foo' it should always be on top. And I also want to sort by 'type'. So 'foo' should always be on top, next sort by 'name' and 'type'.

I tried this:

                byNameDefault.sort(function (a, b) {
                    if (a.name == 'foo') {
                        return -1;
                    }
                    var x = a.type.toLowerCase();
                    var y = b.type.toLowerCase();
                    return x < y ? -1 : x > y ? 1 : 0;
                });

But that didn't work.

And I have no clue how to sort by 'name' AND 'type'.

Any help is much appreciated.

2 Answers 2

2

For multiple sort criteria you proceed from the first to the last criterion: If the two entries for one criterion are not equal, you can return from the sort function with result -1 or 1. Additionally at the last criterion you also can return 0 for two equal inputs.

Here is an example implementation for your case:

byNameDefault.sort(function (a, b) {
    // compare names
    var na = a.name.toLowerCase();
    var nb = b.name.toLowerCase();

    if (na !== nb) {
        if (na === 'foo')
            return -1;
        else if (nb === 'foo')
            return 1;
        else
            return na < nb ? -1 : 1;
    } 

    // compare types
    return a.type < b.type ? -1 : a.type > b.type ? 1 : 0; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer and the explanation. I now understand what I'm doing ;)
0

Do this in one expression where the different components are combined with ||; only when one part evaluates to 0, then next one comes into play:

byNameDefault.sort(function (a, b) {
    return (b === 'foo') - (a == 'foo') || 
           a.name.localeCompare(b.name) ||
           a.type.localeCommpare(b.type); 
}

Comments

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.