EN
TypeScript - weighted arithmetic mean
0 points
In this article, we would like to show you how to calculate the weighted arithmetic mean value in TypeScript.
Runnable example:
xxxxxxxxxx
1
const calculateWeightedAverage = (values: number[], weights: number[]): number => {
2
if (values.length !== weights.length) {
3
throw new Error('Values and weights arrays must have same size.');
4
}
5
let a = 0;
6
let b = 0;
7
for (let i = 0; i < values.length; ++i) {
8
const weight = weights[i];
9
a += weight * values[i];
10
b += weight;
11
}
12
return a / b;
13
};
14
15
16
// Usage example:
17
18
// Let's suppose we have: 4x 3.0, 9x 4.0 and 4x 5.0
19
20
const marks: number[] = [3.0, 4.0, 5.0];
21
const counts: number[] = [4, 9, 4];
22
23
const average: number = calculateWeightedAverage(marks, counts);
24
25
console.log(average);
Output:
xxxxxxxxxx
1
4