javascript 使用 lodash 按多个字段对数组中的项目进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19313164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort items in array by more then one field with lodash
提问by Andreas K?berle
How can I sort an array of objects by more then one field using lodash. So for an array like this:
如何使用 lodash 按多个字段对一组对象进行排序。所以对于这样的数组:
[
{a: 'a', b: 2},
{a: 'a', b: 1},
{a: 'b', b: 5},
{a: 'a', b: 3},
]
I would expect this result
我希望这个结果
[
{a: 'a', b: 1},
{a: 'a', b: 2},
{a: 'a', b: 3},
{a: 'b', b: 5},
]
回答by Daniel Kaplan
This is much easier in a current version of lodash (2.4.1). You can just do this:
这在当前版本的 lodash (2.4.1) 中要容易得多。你可以这样做:
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"
Warning: See the comments below. This looks like it was briefly called sortByAll
in version 3, but now it's back to sortBy
instead.
警告:请参阅下面的评论。看起来它sortByAll
在第 3 版中曾被短暂调用过,但现在又改回来了sortBy
。