Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by multiple fields in Lodash 2.x

Supposing this array:

var members = [
  {firstName: 'Michael', weight: 2}, 
  {firstName: 'Thierry', weight: 1}, 
  {firstName: 'Steph', weight: 3},
  {firstName: 'Jordan', weight: 3}, 
  {firstName: 'John', weight: 2}
];

I want to sort by weight and for each kind of weight, sorting by firstNames (a nested sort so).

Result would be:

[
  {firstName: 'Thierry', weight: 1}, 
  {firstName: 'John', weight: 2}, 
  {firstName: 'Michael', weight: 2}, 
  {firstName: 'Jordan', weight: 3}, 
  {firstName: 'Steph', weight: 3}
];

I achieve this quickly using Lodash 2.4.1:

return _.chain(members)
    .groupBy('weight')
    .pairs()
    .sortBy(function(e) {
        return e[0];
    })
    .map(function(e){
        return e[1];
    })
    .map(function(e){
        return _.sortBy(e, 'firstName')
    })
    .flatten()
    .value();

Is there a better way to achieve it using Lodash 2.4.1?

like image 236
Mik378 Avatar asked Dec 15 '22 10:12

Mik378


2 Answers

You can chain two sorts:

_(members).sortBy('firstName').sortBy('weight').value()
like image 97
floribon Avatar answered Dec 17 '22 00:12

floribon


It's even in plain Javascript very short.

var members = [
    { firstName: 'Michael', weight: 2 },
    { firstName: 'Thierry', weight: 1 },
    { firstName: 'Steph', weight: 3 },
    { firstName: 'Jordan', weight: 3 },
    { firstName: 'John', weight: 2 }
];

members.sort(function (a, b) {
    return a.weight - b.weight || a.firstName.localeCompare(b.firstName);
});

document.write('<pre>' + JSON.stringify(members, 0, 4) + '</pre>');
like image 35
Nina Scholz Avatar answered Dec 17 '22 00:12

Nina Scholz