I have the following data:
var foo = [
{'MonthNo' : 03, 'CustomerTypeID' : 1 , 'TotalSales' : 45 },
{'MonthNo' : 03, 'CustomerTypeID' : 2 , 'TotalSales' : 64 },
{'MonthNo' : 03, 'CustomerTypeID' : 4 , 'TotalSales' : 89 },
{'MonthNo' : 03, 'CustomerTypeID' : 5 , 'TotalSales' : 42 },
{'MonthNo' : 04, 'CustomerTypeID' : 1 , 'TotalSales' : 66 },
{'MonthNo' : 04, 'CustomerTypeID' : 2 , 'TotalSales' : 78 },
{'MonthNo' : 04, 'CustomerTypeID' : 5 , 'TotalSales' : 20 },
{'MonthNo' : 04, 'CustomerTypeID' : 6 , 'TotalSales' : 10 }
];
I want to convert this into the following
{'MonthNo' : 03, 'CustomerTypeID' : 1 , 'TotalSales' : 198 },
{'MonthNo' : 03, 'CustomerTypeID' : 5 , 'TotalSales' : 42 },
{'MonthNo' : 04, 'CustomerTypeID' : 1 , 'TotalSales' : 144 },
{'MonthNo' : 04, 'CustomerTypeID' : 5 , 'TotalSales' : 20 },
{'MonthNo' : 04, 'CustomerTypeID' : 6 , 'TotalSales' : 10 }
For each MonthNo, except for CustomerTypeID 5 & 6, I want to add up the TotalSales value. For Ex: MonthNo 03 for CustomerTypeID 1,2,4 their TotalSales value is summed up to 198.similarly for MonthNo 04, TotalSales value of CustomerTypeID 1 & 2 is added up to 144.
I tried using the reduce function
var result = foo.reduce(function(obj,item){
// code here
},{});
However , I not able to segregate them to get the desired result.Any help would be appreciated.
reduce. Just use an ordinary loop, and create nested objects that useMonthNoandCustomerTypeIDas keys, and the value is the accumulated sales.