2017-01-02 77 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()'的想法。我已经更新了答案。 –