【问题标题】:Lodash filter unique documentsLodash 过滤唯一文档
【发布时间】:2017-05-16 16:15:24
【问题描述】:

如何过滤当前数据:

[{
    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}
}]

【问题讨论】:

  • 删除相同legs.fno和legs.date和fare.type记录中的高价
  • 相同的legs.fno、legs.date和fare.type

标签: filter lodash


【解决方案1】:

_.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>

【讨论】:

  • 用一个简单的 _.minBy 替换 reduce 函数怎么样?节省几行。
  • 感谢@MauritsRijk 提出_.minBy() 的想法。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2017-07-30
  • 1970-01-01
  • 2021-07-14
  • 2017-01-08
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多