2017-01-02 75 views
0

我怎樣才能篩選當前數據:Lodash過濾器獨特的文件

[{ 
    key: 'T1', 
    legs:[{ fno: 'W321',date: '2017-01-02 18:20:00.000+0200'}], 
    fare: { type: 'B', price: 25 } 
},{ 
    key: 'T1', 
    legs:[{ fno: 'W321', date: '2017-01-02T18:20:00.000+0200'}], 
    fare: { type: 'E', price: 23 } 
},{ 
    key: 'T1', 
    legs:[{ fno: 'W321', date: '2017-01-02T18:20:00.000+0200'}], 
    fare: { type: 'E', price: 20} 
}] 

我想按legs[0].fnolegs[0].datefare.type,並保持各組中價格最低的項目。這是預期的結果:

[{ 
    key: 'T1', 
    legs:[{ fno: 'W321',date: '2017-01-02T18:20:00.000+0200'}], 
    fare: { type: 'B', price: 25} 
},{ 
    key: 'T1', 
    legs:[{ fno: 'W321',date: '2017-01-02T18:20:00.000+0200'}], 
    fare: { type: 'E', price: 20} 
}] 
+0

刪除同一legs.fno和legs.date和fare.type記錄中的高價格 –

+0

相同的legs.fno,legs.date和fare.type –

回答

0

使用_.groupBy()有回調使用_.minBy()通過創建一個字符串進行分組,然後_.map()各組的單個項目:

var data = [{"key":"T1","legs":[{"fno":"W321","date":"2017-01-02 18:20:00.000+0200"}],"fare":{"type":"B","price":25}},{"key":"T1","legs":[{"fno":"W321","date":"2017-01-02T18:20:00.000+0200"}],"fare":{"type":"E","price":23}},{"key":"T1","legs":[{"fno":"W321","date":"2017-01-02T18:20:00.000+0200"}],"fare":{"type":"E","price":20}}]; 
 

 
var result = _(data) 
 
    // group by the combined group keys 
 
    .groupBy(function(o) { 
 
    // extract all group keys and join them to a string 
 
    return _.at(o, ['key', 'legs[0].date', 'fare.type']).join(''); 
 
    }) 
 
    .map(function(group) { 
 
    // get the object object with the minimum fare.price 
 
    return _.minBy(group, 'fare.price'); 
 
    }) 
 
    .value(); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+1

如何更換reduce函數j ust由一個簡單的_.minBy?保存幾行。 –

+0

感謝@MauritsRijk爲'_.minBy()'的想法。我已經更新了答案。 –