weighted average

by sprugman

HTML

<div></div>

JavaScript

var computeWeightedAvg = function (arr, avgField, weightField) {
  var result = 0;
  var fieldSum = 0;
  var totalSum = 0;
  $.each(arr, function (i, row) {
    var total = parseInt(row[weightField], 10);
    var pct = parseFloat(row[avgField]);
    if (total > 0) {
      var countVal = pct * total / 100;
      fieldSum += countVal;
      totalSum += total;
    }
  });
  if (totalSum > 0) {
    result = fieldSum / totalSum * 100;
  }
  return result;
};

var data = [{
  "publisherId": "23",
    "channelId": "959468035",
    "inViewLoadPct": "0",
    "totalSampled": "100",
    "totalImpressions": "853",
    "_id_": "1"
}, {
  "publisherId": "23",
    "channelId": "959465998",
    "inViewLoadPct": "100",
    "totalSampled": "0",
    "totalImpressions": "730",
    "_id_": "2"
}/*, {
  "publisherId": "23",
    "channelId": "959465450",
    "inViewLoadPct": "34.98",
    "totalSampled": "86",
    "totalImpressions": "561",
    "_id_": "3"
}, {
  "publisherId": "23",
    "channelId": "965027847",
    "inViewLoadPct": "21.09",
    "totalSampled": "33",
    "totalImpressions": "267",
    "_id_": "4"
}, {
  "publisherId": "23",
    "channelId": "961740220",
    "inViewLoadPct": "27.92",
    "totalSampled": "53",
    "totalImpressions": "241",
    "_id_": "5"
}, {
  "publisherId": "23",
    "channelId": "962736184",
    "inViewLoadPct": "20.05",
    "totalSampled": "20",
    "totalImpressions": "142",
    "_id_": "6"
}, {
  "publisherId": "23",
    "channelId": "959479476",
    "inViewLoadPct": "75.00",
    "totalSampled": "4",
    "totalImpressions": "44",
    "_id_": "7"
}*/, {
  "publisherId": "23",
    "channelId": "961741887",
    "totalSampled": "0",
    "totalImpressions": "4",
    "_id_": "8"
}];



$(function () {
  var avg = computeWeightedAvg(data, 'inViewLoadPct', 'totalSampled');
  $('div').html(avg);
});