How to order a JSON object by two keys?

前端 未结 2 1628
刺人心
刺人心 2020-12-23 10:39

I have a JSON object that I want to sort by one key first, then by a second key similar to ordering by two columns in SQL. Here is a sample of the JSON I would have:

<
2条回答
  •  清歌不尽
    2020-12-23 11:39

    Here is a generic way to sort an array of objects, with multiple columns:

    var arr = [
        { id:5, name:"Name3" },
        { id:4, name:"Name1" },
        { id:6, name:"Name2" },
        { id:3, name:"Name2" }
    ],
    
    // generic comparison function
    cmp = function(x, y){
        return x > y ? 1 : x < y ? -1 : 0; 
    };
    
    //sort name ascending then id descending
    arr.sort(function(a, b){
        //note the minus before -cmp, for descending order
        return cmp( 
            [cmp(a.name, b.name), -cmp(a.id, b.id)], 
            [cmp(b.name, a.name), -cmp(b.id, a.id)]
        );
    });
    

    To add other columns to sort on, you can add other items in the array comparison.

    arr.sort(function(a, b){
        return cmp( 
            [cmp(a.name, b.name), -cmp(a.id, b.id), cmp(a.other, b.other), ...], 
            [cmp(b.name, a.name), -cmp(b.id, a.id), cmp(b.other, a.other), ...]
        );
    });
    

    EDIT: per @PhilipZ comment below, the array comparison in JS convert them in strings separated by comas.

提交回复
热议问题