Skip to content

Instantly share code, notes, and snippets.

@khangvan
Forked from stekhn/weightedMean.js
Last active June 9, 2019 08:22
Show Gist options
  • Save khangvan/def454cf08e265966899b427707750b7 to your computer and use it in GitHub Desktop.
Save khangvan/def454cf08e265966899b427707750b7 to your computer and use it in GitHub Desktop.
Weighted arithmetic mean (average) in JavaScript

Start with code

To do calcaculating weight mean of prvide of array

function weightedMean(arrValues, arrWeights) {
var result = arrValues.map(function (value, i) {
var weight = arrWeights[i];
var sum = value * weight;
return [sum, weight];
}).reduce(function (p, c) {
return [p[0] + c[0], p[1] + c[1]];
}, [0, 0]);
return result[0] / result[1];
}
weightedMean([251, 360, 210], [0.1, 0.5, 0.7]);
// => 270.8461538461539
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment