Sort array of objects by multiple properties in Javascript

删除回忆录丶 提交于 2020-01-11 12:59:08

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32440346/sort-array-of-objects-by-multiple-properties-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!