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

前端 未结 7 1155
情话喂你
情话喂你 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:40

    If the problem is an integer is converted to a string, add zeroes before the integer to make it have the same length as the longest in the collection:

    var maxLength = _.reduce(data, function(result, item) {
        var bString = _.toString(item.sortData.b);
        return result > bString.length ? result : bString.length;            
    }, 0);
    
    _.sortBy(data, function(item) {
        var bString = _.toString(item.sortData.b);
        if(maxLength > bString.length) {
            bString = [new Array(maxLength - bString.length + 1).join('0'), bString].join('');
        }
    
        return [item.sortData.a, bString];
    });
    

提交回复
热议问题