简体   繁体   中英

Sort array of objects by multiple properties in Javascript

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM