按照Lodash 2.x中的多个字段排序

时间:2015-11-25 22:58:30

标签: javascript sorting lodash

假设这个数组:

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

我想按重量和每种重量排序,按firstNames排序(嵌套排序等)。

结果将是:

[
  {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有没有更好的方法来实现它?

3 个答案:

答案 0 :(得分:6)

您可以链接两种类型:

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

答案 1 :(得分:4)

它甚至在简单的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>');

答案 2 :(得分:0)

如果您使用旧版本的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 result = _.sortBy(成员,[&#39;名字&#39;,&#39;权重&#39;],[&#39; asc&#39;,&#39; asc&#39; ]);

console.log(&#39;结果&#39;,结果);