如何使用underscore.js对文本混合数字进行排序

时间:2015-12-05 16:52:03

标签: javascript angularjs node.js underscore.js

我对_.sortBy(underscore.js)的排序值有一些问题。并且 我有这样的价值:

[
  {
    first: A,
    second: 10,
    third: D3
  }
  {
    first: B,
    second: 2,
    third: F3
  }
  {
    first: C,
    second: 3,
    third: G4
  }
  {
    first: A,
    second: 9,
    third: G5
  }
]

我尝试用以下方式对其进行排序:

var sortedArray = _.sortBy(list_data, function(data) {
   return [data[0].first, data[0].second.join("_");
});

总是返回[{first:A,second:10,third:D3}, {first:A,second:9,third:G6}, {first:B,second:2,third:F3}, {first:C,second:3,third:G4}]

但我希望它像[{first:A,second:9,third:G6}, {first:A,second:10,third:D3}, {first:B,second:2,third:F3}, {first:C,second:3,third:G4}]

一样返回

我该怎么办?请求帮助,我是这方面的新手。非常感谢你。

2 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

var array = [
  {
    first: 'C',
    second: 3,
    third: 'D3'
  },
  {
    first: 'A',
    second: 9,
    third: 'G5'
  }
];

var sorted = array.sort(function(a, b) {
   var first = a.first + a.second + a.third;
   var second = b.first + b.second + b.third;
   return first.localeCompare(second);
});

答案 1 :(得分:0)

var sortedArray = _(list_data)
                  .chain()
                  .sortBy(function(data){
                    return data.second;
                  })
                  .sortBy(function(data){
                    return data.first;
                  })
                  .value();