46

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},
]
MMalke
  • 1,857
  • 1
  • 24
  • 35
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297

1 Answers1

67

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.

bgschiller
  • 2,087
  • 1
  • 16
  • 30
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 13
    This does not work as of v3.0.0. The syntax is correct but the method to use is `_.sortByAll(data, ["a", "b"]);` The difference between `_.sortBy` and `_.sortByAll` is `_.sortBy` sorts off of an iteratee and `_.sortByAll` sorts by property names. [api reference](https://lodash.com/docs#sortByAll) and [changelog](https://github.com/lodash/lodash/wiki/Changelog#v300) – nwayve Jan 29 '15 at 20:26
  • 5
    _.sortByAll no longer exists in v4.0. https://github.com/lodash/lodash/wiki/Changelog – backdesk Apr 08 '16 at 21:26
  • 4
    `_.sortByAll` works great in 3.10. In 4.0+ use `_.sortBy`. Thanks! – Stepan Zakharov May 17 '17 at 13:51
  • 30
    You can also add third parameter (order direction) like `_.orderBy(collection, ['fieldA', 'fieldB'], ['asc', 'desc']);` – Nozim Turakulov Jan 27 '19 at 13:42