EN
JavaScript - weighted arithmetic mean
10
points
In this article, we would like to show you how to calculate the weighted arithmetic mean value in JavaScript.
Runnable example:
// ONLINE-RUNNER:browser;
const calculateWeightedAverage = (values, weights) => {
if (values.length !== weights.length) {
throw new Error('Values and weights arrays must have same size.');
}
let a = 0;
let b = 0;
for (let i = 0; i < values.length; ++i) {
const weight = weights[i];
a += weight * values[i];
b += weight;
}
return a / b;
};
// Usage example:
// Let's suppose we have: 4x 3.0, 9x 4.0 and 4x 5.0
const marks = [3.0, 4.0, 5.0];
const counts = [4, 9, 4];
const average = calculateWeightedAverage(marks, counts);
console.log(average); // 4