Reputation: 15982
I perform a series of operations (originally using underscore) on an array of objects that found the sales value for the month with the highest sales.
The data: The values
array represents the total sales for a given month. x
= date, y
= sales.
[
{
name:'banana',
values:[
{
x: //date object: jan 2016,
y: 3423
},
{
x: //date object: feb 2016,
y: 53453
},
{
x: //date object: mar 2016,
y: 65457
},
{
x: //date object: apr 2016,
y: 456345
},
...//12 months
]
},
{
name:'apple',
values:[
{
x: //date object: jan 2016,
y: 34876
},
{
x: //date object: feb 2016,
y: 89
},
{
x: //date object: mar 2016,
y: 7896
},
{
x: //date object: apr 2016,
y: 6547
},
...//12 months
]
},
... more objects
]
My function: Returns the highest sales amount out of all months.
getMaxMonthlySales:function(data){
var salesArrays = _.map(data,obj=>_.map(obj.values,'y'))
var maxSales = _.zip.apply(null,salesArrays)
maxSales = _.reduce(maxSales,(max,arr)=>{
var sum = _.reduce(arr,(memo,val)=>memo+val);
return Math.max(max,sum);
},0)
return maxSales;
}
All values
arrays per object are guaranteed to be the same length and have the same order of dates. My general strategy is to perform a nested map to obtain an array of arrays of only sales. Then zip the arrays to group sales by month. Then finally reduce each month to find the total sales per month, then find the maximum month.
My question is how can i rewrite this function as ideally a lodash chain?
Upvotes: 0
Views: 56
Reputation: 9985
As a oneliner:
getMaxMonthlySales: function(data) {
return _.max(_.map(_.groupBy(_.flatten(_.map(data, 'values')), 'x'),
o => _.sumBy(o, 'y')));
}
Or
getMaxMonthlySales: function(data) {
return _(data)
.map('values')
.flatten()
.groupBy('x')
.map(o => _.sumBy(o, 'y'))
.max();
}
Upvotes: 1