Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created July 25, 2022 11:59
Show Gist options
  • Save yano3nora/639ce4e4a66a26749fe51d530a444918 to your computer and use it in GitHub Desktop.
Save yano3nora/639ce4e4a66a26749fe51d530a444918 to your computer and use it in GitHub Desktop.
[js: percent-weighted-average] 単純なパーセント配分のお重みで加重平均出すやつ #js
/**
* 単純な 100% の配分で重み付けできる「値:重み」の列挙から、加重平均値を導出する
*
* @link https://jp.indeed.com/career-advice/career-development/how-to-calculate-weighted-average
* @example percentWeightedAvg([
* { value: 150, weight: 320 },
* { value: 200, weight: 180 },
* ]) // 168
*/
const percentWeightedAvg = (data = [{ value: 0, weight: 0 }]) => {
const sumOfWeight = data.reduce((a, d) => a + d.weight, 0)
return data.reduce((a, d) => (
a + (
d.value * (d.weight / sumOfWeight)
)
), 0)
}
console.log(
percentWeightedAvg([
{ value: 150, weight: 320 },
{ value: 200, weight: 180 },
])
) // 168
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment