用lodash将数组中的项目按多个字段排序 [英] Sort items in an array by more than one field with lodash
本文介绍了用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);});
它将输出到控制台:
"a 1"
"a 2"
"a 3"
"b 5"
警告:请参阅下面的评论.看起来好像在版本3中被简称为 sortByAll
,但现在又回到了 代替
.
Warning: See the comments below. This looks like it was briefly called sortByAll
in version 3, but now it's back to sortBy
instead.
这篇关于用lodash将数组中的项目按多个字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文