简体   繁体   中英

Sort items in an array by more than one field with 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},
]

I would expect this result

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

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"

Warning: See the comments below. This looks like it was briefly called sortByAll in version 3, but now it's back to sortBy instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM