2015-11-25 48 views
4

多個字段假設此數組:排序在Lodash 2.x的

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

我想要(重量)以及對於每個種類重量的排序,通過firstNames分選(嵌套排序左右)。

結果將是:

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

我實現這個快速使用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(); 

有沒有更好的方式使用Lodash 2.4.1實現呢?

回答

6

你可以連續兩類:

_(members).sortBy('firstName').sortBy('weight').value() 
+1

我提這個作品,因爲lodash的sortBy採用了穩定的排序 –

+0

我不知道哪個回答我要選:)每一個解決方案是優雅。 – Mik378

+0

我並不知道這種類型的穩定性。 – Mik378

4

它甚至在普通的JavaScript很短。

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>');

+2

這是一個非常聰明的方法 – Mik378