2017-10-19 138 views
1

我有一個數組:Lodash ORDERBY對象

const names = [{name: 'a', equal: 3}, 
{name: 'b', equal: 2}, 
{name: 'c', equal: 2}, 
{name: 'd', equal: 3}, 
{name: 'a1', equal: 1}] 

我運行_.groupBy(名稱, '等於'),結果獲得:

{1: [{equal: 1, name: 'a1'}], 
2: [{equal: 2, name: 'b'}, {equal: 2, name: 'c'}], 
3: [{equal: 3, name: 'a'}, {equal: 3, name: 'd'}]} 

但在這裏按名稱排序消失。如何在此對象中按名稱排序?

更新

我想:

{3: [{equal: 3, name: 'a'}, {equal: 3, name: 'd'}], 
1: [{equal: 1, name: 'a1'}], 
2: [{equal: 2, name: 'b'}, {equal: 2, name: 'c'}]} 
+0

所以要排序相等,然後通過名稱爲對象進行排序以相同的平等嗎? –

+0

是的,我想得到:{3:[{equal:3,name:'a'},{equal:3,name:'d'}]​​, 1:[{equal:1,name:'a1 '}], 2:[{equal:2,name:'b'},{equal:2,name:'c'}]} – user5671335

+0

對象有沒有順序或在即將到來的JS中,順序是帶整數值。 –

回答

1

通過使用數組作爲結果集,可以在分組後對其進行排序。

var names = [{ name: 'a', equal: 3 }, { name: 'b', equal: 2 }, { name: 'c', equal: 2 }, { name: 'd', equal: 3 }, { name: 'a1', equal: 1 }], 
 
    equals = {}, 
 
    result = []; 
 

 
names.forEach(function (o) { 
 
    if (!equals[o.equal]) { 
 
     equals[o.equal] = []; 
 
     result.push(equals[o.equal]); 
 
    } 
 
    equals[o.equal].push(o); 
 
}); 
 

 
result.sort(function (a, b) { 
 
    return a[0].name.localeCompare(b[0].name); 
 
}); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

可以使用lodash方法GROUPBY和sortBy一起

DEMO

const names = [{name: 'a', equal: 3}, 
 
{name: 'b', equal: 2}, 
 
{name: 'c', equal: 2}, 
 
{name: 'd', equal: 3}, 
 
{name: 'a1', equal: 1}]; 
 

 
var grouped = _.groupBy(names, function(name) { 
 
    return name.equal; 
 
}); 
 
var result = _.sortBy(grouped, ['name']); 
 
console.log(grouped);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

+0

與_.groupBy(names,'equal')的區別? – user5671335

+0

抱歉誤解了 – Sajeetharan

+0

這個不行! – user5671335