How can I use lodash/underscore to sort by multiple nested fields?

前端 未结 7 1173
情话喂你
情话喂你 2021-02-03 21:51

I want to do something like this:

var data = [
    {
        sortData: {a: \'a\', b: 2}
    },
    {
        sortData: {a: \'a\', b: 1}
    },
    {
        sort         


        
7条回答
  •  花落未央
    2021-02-03 22:32

    There is a _.sortByAll method in lodash version 3:

    https://github.com/lodash/lodash/blob/3.10.1/doc/README.md#_sortbyallcollection-iteratees

    Lodash version 4, it has been unified:

    https://lodash.com/docs#sortBy

    Other option would be to sort values yourself:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    function compareValues(v1, v2) {
        return (v1 > v2) 
            ? 1 
            : (v1 < v2 ? -1 : 0);
    };
    
    
    var data = [
        { a: 2, b: 1 },
        { a: 2, b: 2 },
        { a: 1, b: 3 }
    ];
    
    data.sort(function (x, y) {
        var result = compareValues(x.a, y.a);
    
        return result === 0 
            ? compareValues(x.b, y.b) 
            : result;
    });
    
    // data after sort:
    // [
    //     { a: 1, b: 3 },
    //     { a: 2, b: 1 },
    //     { a: 2, b: 2 }
    // ];
    

提交回复
热议问题