Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active September 25, 2024 03:23
Show Gist options
  • Select an option

  • Save stekhn/a12ed417e91f90ecec14bcfa4c2ae16a to your computer and use it in GitHub Desktop.

Select an option

Save stekhn/a12ed417e91f90ecec14bcfa4c2ae16a to your computer and use it in GitHub Desktop.
Weighted arithmetic mean (average) in JavaScript
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
@afuggini

afuggini commented Sep 9, 2018

Copy link
Copy Markdown

I implemented it this way:
https://gist.github.com/afuggini/ccc74896676751b50f471ec571ea9f5d

const sumArrayValues = (values) => {
  return values.reduce((p, c) => p + c, 0)
}

const weightedMean = (factorsArray, weightsArray) => {
  return sumArrayValues(factorsArray.map((factor, index) => factor * weightsArray[index])) / sumArrayValues(weightsArray)
}

weightedMean([251, 360, 210], [0.1, 0.5, 0.7]);
// => 270.8461538461539

@verekia

verekia commented Jan 3, 2020

Copy link
Copy Markdown

Thank you very much!

Here is the TypeScript / ES6 variation for people who are allergic to var and function:

export const weightedMean = (arrValues: number[], arrWeights: number[]) => {
  const result = arrValues
    .map((value, i) => {
      const weight = arrWeights[i]
      const sum = value * weight
      return [sum, weight]
    })
    .reduce((p, c) => [p[0] + c[0], p[1] + c[1]], [0, 0])

  return result[0] / result[1]
}

@stekhn

stekhn commented Jan 7, 2020

Copy link
Copy Markdown
Author

@verekia Nice work! I'll use that one in the future ๐Ÿ‘

@abrkn

abrkn commented Jul 10, 2020

Copy link
Copy Markdown
const tuples = [
    [100, 1],
    [200, 2],
    [300, 3]
];

const [valueSum, weightSum] = tuples.reduce(([valueSum, weightSum], [value, weight]) =>
    ([valueSum + value * weight, weightSum + weight]), [0, 0]);

console.log(valueSum / weightSum); // 233.333..4

@franceindia

franceindia commented Aug 26, 2022

Copy link
Copy Markdown

Here is another way to do it. This is subjective but I like to break out variables because I find it easier to read.:

const tuples = [
    [100, 1],
    [200, 2],
    [300, 3]
]
const weightSum = tuples.reduce((accumulator, item) => accumulator + item[1], 0)
const weightedAverage = tuples.reduce((accumulator, item) => accumulator + item[0] * item[1] / weightSum, 0)

@WolfieWerewolf

Copy link
Copy Markdown

@franceindia

I very much like this approach, it is perfect for my use case. Thank you for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment