【问题标题】:Sort by multiple fields in Lodash 2.x在 Lodash 2.x 中按多个字段排序
【发布时间】:2015-11-25 22:58:29
【问题描述】:

假设这个数组:

var members = [
  {firstName: 'Michael', weight: 2}, 
  {firstName: 'Thierry', weight: 1}, 
  {firstName: 'Steph', weight: 3},
  {firstName: 'Jordan', weight: 3}, 
  {firstName: 'John', weight: 2}
];

我想按重量排序,对于每种重量,按名字排序(嵌套排序)。

结果是:

[
  {firstName: 'Thierry', weight: 1}, 
  {firstName: 'John', weight: 2}, 
  {firstName: 'Michael', weight: 2}, 
  {firstName: 'Jordan', weight: 3}, 
  {firstName: 'Steph', weight: 3}
];

我使用Lodash 2.4.1 快速实现了这一点:

return _.chain(members)
    .groupBy('weight')
    .pairs()
    .sortBy(function(e) {
        return e[0];
    })
    .map(function(e){
        return e[1];
    })
    .map(function(e){
        return _.sortBy(e, 'firstName')
    })
    .flatten()
    .value();

有没有更好的方法来使用 Lodash 2.4.1 实现它?

【问题讨论】:

    标签: javascript sorting lodash


    【解决方案1】:

    你可以链接两种:

    _(members).sortBy('firstName').sortBy('weight').value()
    

    【讨论】:

    • 我会提到这个工作,因为 lodash 的 sortBy 使用稳定的排序
    • 我不知道我应该投票给哪个答案 :) 每个解决方案都很优雅。
    • 我不知道排序的稳定性。
    • 您询问了使用 lodash 的解决方案 :-) 但是我建议您尽可能使用纯 JS,特别是如果您要执行很多此类操作:它总是更快、更高效跨度>
    【解决方案2】:

    它甚至在纯 Javascript 中也很短。

    var members = [
        { firstName: 'Michael', weight: 2 },
        { firstName: 'Thierry', weight: 1 },
        { firstName: 'Steph', weight: 3 },
        { firstName: 'Jordan', weight: 3 },
        { firstName: 'John', weight: 2 }
    ];
    
    members.sort(function (a, b) {
        return a.weight - b.weight || a.firstName.localeCompare(b.firstName);
    });
    
    document.write('<pre>' + JSON.stringify(members, 0, 4) + '</pre>');

    【讨论】:

    • 这是一个非常聪明的方法
    【解决方案3】:

    如果您使用的是旧版本的 lodash,则使用 lodash 的另一种变体

    var members = [
    { firstName: 'Michael', weight: 2 },
    { firstName: 'Thierry', weight: 1 },
    { firstName: 'Steph', weight: 3 },
    { firstName: 'Jordan', weight: 3 },
    { firstName: 'John', weight: 2 }
    

    ];

    var 结果 = _.sortBy(members, ['firstname', 'weight'], ['asc', 'asc']);

    console.log('结果', 结果);

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 2016-05-15
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多