简体   繁体   English

Loadash对多列进行分组和求和

[英]Loadash group and sum multiple columns

In my Vue app I need to group an array by date and then sum multiple columns.在我的 Vue 应用程序中,我需要按日期对数组进行分组,然后对多列求和。 I was able to group and sum 1 column this way:我能够以这种方式对 1 列进行分组和求和:

receiptsByDate: function(){
   let byDate = _.groupBy(this.receipts, 'date');
   let totals = {};
   _.forEach(byDate, function(amounts, Date){
   totals[Date] = _.reduce( byDate[Date], function(sum, receipt){
   return sum + parseFloat( receipt.total );
   }, 0);
   })
   return totals;   
}

which creates an object date: total.它创建了一个 object 日期:总计。

This is a receipt sample on which the function is applied:这是应用了 function 的收据样本:

card_commission:null
created_at:"2019-11-14 06:13:20"
customer_id:null
date:"2019-11-14"
discount:"12000.0"
id:1
location_id:null
number:"2019-00001"
service:null
subtotal:"200000.0"
table_id:null
taxes:null
ticket_id:1
total:"188000.0"
updated_at:"2019-11-14 06:13:20"

I need instead to group by date but beside receipt.total I need to sum other columns like discount, subtotal and so on.我需要按日期分组,但在receipt.total 旁边,我需要对折扣、小计等其他列进行求和。 I did not find anything online to achieve this.我没有在网上找到任何东西来实现这一点。 Anyone can point me in the right direction?任何人都可以指出我正确的方向吗? It doesn't have to be with loadash another approach is ok too.它不必与 loadash 一起使用,另一种方法也可以。

Instead of returning only total, you can return an object consist of all computed values for every date.您可以返回一个包含每个日期的所有计算值的 object,而不是只返回总计。

receiptsByDate: function(){
  let byDate = _.groupBy(this.receipts, 'date');

  let computedData = {};
  _.forEach(byDate, function(receiptList, date){
    computedData[date] = {
      total: _.sumBy(receiptList, function(receipt) {
        return parseFloat(receipt.total);
      }),
      discount: _.sumBy(receiptList, function(receipt) {
        return parseFloat(receipt.discount);
      })
    }
  };

  return computedData;
}

Change reduce to another forEach.将 reduce 更改为另一个 forEach。 If you want to use Date as key, then如果你想使用 Date 作为键,那么

let sumary = {}
_.forEach(byDate[Date], (receipt) => {
   if(sumary.total == null)
      sumary.total = parseFloat(receipt.total)
   else
      sumary.total += parseFloat(receipt.total)

   if(sumary.other== null)
      sumary.other= parseFloat(receipt.other)
   else
      sumary.other+= parseFloat(receipt.other)
}
totals[Date] = summary

If this is what you want, then you could improve your code, just replace 0 with { total: 0, other: 0} and calculate inside the reduce function.如果这是您想要的,那么您可以改进您的代码,只需将 0 替换为 { total: 0, other: 0} 并在 reduce function 中计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM