使用lodash按多个字段对数组中的项进行排序 [英] Sort items in array by more then one field with lodash

查看:2276
本文介绍了使用lodash按多个字段对数组中的项进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用lodash通过多个字段对对象数组进行排序。所以对于这样的数组:

How can I sort an array of objects by more then one field using lodash. So for an array like this:

[
  {a: 'a', b: 2},
  {a: 'a', b: 1},
  {a: 'b', b: 5},
  {a: 'a', b: 3},
]

我希望这个结果

[
  {a: 'a', b: 1},
  {a: 'a', b: 2},
  {a: 'a', b: 3},
  {a: 'b', b: 5},
]


推荐答案

这在当前版本的lodash(2.4.1)中要容易得多。您可以这样做:

This is much easier in a current version of lodash (2.4.1). You can just do this:

var data = [
    {a: 'a', b: 2},
    {a: 'a', b: 1},
    {a: 'b', b: 5},
    {a: 'a', b: 3},
];

data = _.sortBy(data, ["a", "b"]);  //key point: Passing in an array of key names

_.map(data, function(element) {console.log(element.a + " " + element.b);});

它会将此输出到控制台:

And it will output this to the console:

"a 1"
"a 2"
"a 3"
"b 5"

警告:请参阅以下评论。这看起来在版本3中简称为 sortByAll ,但现在又回到 sortBy

这篇关于使用lodash按多个字段对数组中的项进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆