Sort items in an array by more than one field with lodash

Andreas Köberle picture Andreas Köberle · Oct 11, 2013 · Viewed 31.4k times · Source

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},
]

Answer

Daniel Kaplan picture Daniel Kaplan · Jun 9, 2014

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.