Tuesday, April 2, 2013

Computing the weighted mean


Recently I was asked to compute the weighted average over aggregating some shipments and coming up with a average price paid per lb for each product. Hope someone finds it useful, and remember you need underscore.

function avgBetterReduce(purchases) {
  var weightedAvgs = [];

  _.each(_.reduce(purchases, function(memo, p) {
      // If we haven't seen the product yet intialize the object memo[product]
      memo.hasOwnProperty(p.product) ? 0 : memo[p.product] = { avg: 0, totalLbs: 0};
     
      memo[p.product] = { avg: memo[p.product].avg + p.costPerLb * p.lbs, totalLbs: memo[p.product].totalLbs + p.lbs };
      return memo;
    }, {}), /* Function to handle the resulting map from reduce */ function(value, key) {
        weightedAvgs.push({ product: key, avgCost: value.avg / value.totalLbs });
    });

  return weightedAvgs;
}

Input something like the following:


var purchases = [
  {"product":"Apricots","lbs":877,"costPerLb":"1.32"},
  {"product":"Figs","lbs":1557,"costPerLb":"2.11"},
  {"product":"Celery","lbs":1314,"costPerLb":"1.00"},
  {"product":"Tomatos","lbs":645,"costPerLb":"0.26"},
  {"product":"Guava","lbs":1928,"costPerLb":"0.84"},
  {"product":"Celery","lbs":1503,"costPerLb":"0.87"},
  {"product":"Lettuce","lbs":1546,"costPerLb":"0.82"},
  {"product":"Celery","lbs":1119,"costPerLb":"0.78"},
  {"product":"Apples","lbs":583,"costPerLb":"0.36"},
  {"product":"Apples","lbs":1272,"costPerLb":"0.42"},
  {"product":"Pears","lbs":127,"costPerLb":"0.84"},
  {"product":"Tomatos","lbs":1992,"costPerLb":"0.29"},
  {"product":"Apricots","lbs":1426,"costPerLb":"1.28"},
  {"product":"Apricots","lbs":1045,"costPerLb":"1.71"},
  {"product":"Celery","lbs":1633,"costPerLb":"1.14"}
];

Output will look similar:


[ { product: 'Apricots', avgCost: 1.4236599007668016 },
  { product: 'Figs', avgCost: 1.9670220089046067 },
  { product: 'Celery', avgCost: 0.9623391958858117 },
  { product: 'Tomatos', avgCost: 0.30542861699968105 },
  { product: 'Guava', avgCost: 0.9120219665767172 },
  { product: 'Lettuce', avgCost: 0.8001419032810235 },
  { product: 'Apples', avgCost: 0.3580237647589682 },
  { product: 'Pears', avgCost: 0.8805333538010198 } ]

No comments:

Post a Comment