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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:08:31  来源:igfitidea点击:

Sort items in array by more then one field with lodash

javascriptunderscore.jslodash

提问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 sortByAllin version 3, but now it's back to sortByinstead.

警告:请参阅下面的评论。看起来它sortByAll在第 3 版中曾被短暂调用过,但现在又改回来了sortBy