我有一个对象数组,我想按日期排序,然后按颜色排序,并使用lodash对事件进行求和
InitialArray = [{"date":"2017-07-26","partner":"partner1","total":102,"occurrence":10},{"date":"2017-07-27","partner":"partner1","total":100,"occurrence":20},{"date":"2017-07-27","partner":"partner1","total":110,"occurrence":25},{"date":"2017-07-27","partner":"partner2","total":105,"occurrence":30}]
我需要按日期排序,然后按合作伙伴排序,并汇总给定日期的总计和发生次数。 所以我的最终数组需要看起来像:
FinalArray = [{"date":"2017-07-26","partner":"partner1","total":102,"occurrence":10},{"date":"2017-07-27","partner":"partner1","total":210,"occurrence":45},{"date":"2017-07-27","partner":"partner2","total":105,"occurrence":30}]
我能够以非功能方式获得结果,但我想优化代码并使用lodash以功能方式执行,因为项目已经在使用它。我能够找到一个我可以组合的示例在给定列上,然后使用sum运算符聚合其他字段。但无法找到任何组合2个字段然后聚合的例子。任何帮助表示赞赏。
答案 0 :(得分:1)
您可以先对项目进行分组,然后映射聚合值。
Order
Transaction
OrderProduct
TransactionDetail
order_product_id // <- needing this is assumed
transaction_id // <- but also needs this
&#13;
var initialArray = [{ date: "2017-07-26", partner: "partner1", total: 102, occurrence: 10 }, { date: "2017-07-27", partner: "partner1", total: 100, occurrence: 20 }, { date: "2017-07-27", partner: "partner1", total: 110, occurrence: 25 }, { date: "2017-07-27", partner: "partner2", total: 105, occurrence: 30 }],
groups = ['date', 'partner'],
result = _(initialArray)
.groupBy(o => groups.map(k => o[k]).join('|'))
.map((a, k) => ({
date: a[0].date,
partner: a[0].partner,
total: _.sumBy(a, 'total'),
occurrence: _.sumBy(a, 'occurrence')
}))
.value();
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:0)
我认为这会产生你想要的结果。
var a = [ {"date":"2017-07-26","partner":"partner1","total":102,"occurrence":10},
{"date":"2017-07-27","partner":"partner1","total":100,"occurrence":20},
{"date":"2017-07-27","partner":"partner1","total":110,"occurrence":25},
{"date":"2017-07-27","partner":"partner2","total":105,"occurrence":30}
];
var out = a.reduce( (s,e,i) => {
if (i === 0)
s.push(e);
else
if (typeof s.find( ss => ss.date == e.date && ss.partner == e.partner && (ss.total += e.total)) == 'undefined')
s.push(e);
return s;
}, []);
console.log( out );
&#13;