Calculate a weighted mean in JavaScript
Intermediate · 4 min read
A normal average treats every value the same. Often they shouldn't count the same. A final exam is worth more than a homework quiz. A product rating from 500 buyers should count more than one from 2 buyers. When some values count more than others, you need a weighted mean.
In this tutorial you will work out a course grade where coursework is worth 10%, the midterm 30% and the final 60%. The student scored 75, 62 and 88. Along the way you will see why the way you write the weights changes the last digit of the answer. You need to know arrays, a for loop and the plain average.
What a weight does
A weight says how much a value counts. To get a weighted mean:
- Multiply each value by its weight.
- Add those products up.
- Divide by the total of the weights, not by the number of values.
For our student that is (10 × 75 + 30 × 62 + 60 × 88) ÷ (10 + 30 + 60), which is 7890 ÷ 100 = 78.9.
A plain average is just the special case where every weight is 1. Then the total of the weights equals the count, and you get the formula you already know.
Why the way you write weights matters
Computers store numbers in binary. Whole numbers like 10 and 30 are stored exactly. Decimals like 0.1 and 0.3 are not: each is stored as the nearest binary fraction, a tiny bit off. Each small error is harmless alone, but they can add up and show in the last digit.
console.log(10 * 75); // 750
console.log(0.1 * 75); // 7.5
console.log(0.1 + 0.2); // 0.30000000000000004
Keep that in mind. It will come back in Step 3.
Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.
62 The weighted mean
fairA course grade is 10% coursework, 30% midterm and 60% final, and a student scored 75, 62 and 88. Work out the grade, keeping the weights as whole percentages, and compare it with the same sum done in decimal weights.
Stuck? Three hints, smallest first
- 1. Multiply each value by its weight, add, then divide by the total weight — not by the count.
- 2. Whole-number weights keep the numerator exact and leave a single division at the end.
- 3. Equal weights must reproduce the plain mean; if they do not, the divisor is wrong.
Step 1: write the function
Two running totals do all the work: top collects the value-times-weight products, and bottom collects the weights.
function weightedMean(xs, ws) {
let top = 0;
let bottom = 0;
for (let i = 0; i < xs.length; i++) {
top += xs[i] * ws[i];
bottom += ws[i];
}
return top / bottom; // divide by the weight total, not the count
}
xs[i] and ws[i] share the same index, so the loop pairs each score with its own weight.
Step 2: the grade, with whole-number weights
const scores = [75, 62, 88];
const percent = [10, 30, 60]; // whole numbers, summing to 100
console.log(10 * 75 + 30 * 62 + 60 * 88); // 7890
console.log(weightedMean(scores, percent)); // 78.9
Every product is a whole number, so top is exactly 7890. There is only one division at the end, so only one rounding, and the result is the double closest to 78.9.
A common slip here is dividing by xs.length, which is 3. That gives 2630, which is so obviously wrong you would spot it at once.
Step 3: the same weights as decimals
Many people write 10%, 30% and 60% as 0.1, 0.3 and 0.6:
const decimal = [0.1, 0.3, 0.6]; // the same weights, as fractions
console.log(weightedMean(scores, decimal)); // 78.89999999999999
console.log(weightedMean(scores, decimal) === 78.9); // false
This is the drift from earlier. 0.1, 0.3 and 0.6 are each slightly off, their products with the scores are slightly off, and the sum ends up one tiny step below 78.9. A check like grade === 78.9 would fail, a report card could print 78.89999999999999, and a "78.9 or more" grade band could reject the student.
The fix is simple: keep weights as whole numbers when you can, and divide once at the end.
Step 4: only the ratio matters
Because we divide by the weight total, scaling every weight by the same amount changes nothing. 10:30:60 is the same weighting as 1:3:6.
const raw = [1, 3, 6]; // unnormalised, and it makes no difference
console.log(weightedMean(scores, raw)); // 78.9
"Unnormalised" means the weights don't add up to 1 or 100. That is fine here, because the division takes care of it.
Step 5: compare with the plain mean
const plain = scores.reduce((a, b) => a + b, 0) / scores.length;
console.log(plain); // 75
console.log(weightedMean(scores, [1, 1, 1])); // 75
console.log(weightedMean(scores, percent) - plain); // 3.9000000000000057
Equal weights give back the plain mean, 75, which is a good test that your divisor is right. The weighting is worth about 3.9 marks to this student, because the best score (88) is on the heaviest exam. The subtraction prints 3.9000000000000057, the same kind of last-digit error as Step 3.
Step 6: weights that add up to zero
console.log(weightedMean(scores, [0, 0, 0])); // NaN
With every weight 0, both totals are 0, and 0 / 0 is NaN (Not a Number). That is the honest answer: there is nothing to average. If your app can get all-zero weights, check for it and decide what to show.
The full solution
The answer panel has weightedMean and runs it with percentage, decimal and 1:3:6 weights, then prints the plain mean, the equal-weights case and the all-zero case. Press Run to see the output.
function weightedMean(xs, ws) {
let top = 0;
let bottom = 0;
for (let i = 0; i < xs.length; i++) {
top += xs[i] * ws[i];
bottom += ws[i];
}
return top / bottom; // divide by the weight total, not the count
}
const scores = [75, 62, 88];
const percent = [10, 30, 60]; // whole numbers, summing to 100
const decimal = [0.1, 0.3, 0.6]; // the same weights, as fractions
const raw = [1, 3, 6]; // unnormalised, and it makes no difference
const plain = scores.reduce((a, b) => a + b, 0) / scores.length;
console.log('numerator :', 10 * 75 + 30 * 62 + 60 * 88, 'over 100');
console.log('weighted grade :', weightedMean(scores, percent));
console.log('decimal weights:', weightedMean(scores, decimal), '<- one bit low');
console.log('raw weights :', weightedMean(scores, raw));
console.log('unweighted mean:', plain);
console.log('equal weights :', weightedMean(scores, [1, 1, 1]));
console.log('zero weights :', weightedMean(scores, [0, 0, 0]));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the weighted grade is 78.9, from 7890 over 100', [10 * 75 + 30 * 62 + 60 * 88, weightedMean(scores, percent)], [7890, 78.9]);
test('the decimal weights give 78.89999999999999 instead', weightedMean(scores, decimal), 78.89999999999999);
test('so the two routes are not equal, though both are "right"', weightedMean(scores, decimal) === weightedMean(scores, percent), false);
test('scaling every weight changes nothing, so 1:3:6 also gives 78.9', weightedMean(scores, raw), 78.9);
test('the unweighted mean is 75, so the weighting is worth 3.9 marks', [plain, weightedMean(scores, percent) - plain], [75, 3.9000000000000057]);
test('equal weights reproduce the plain mean exactly', weightedMean(scores, [1, 1, 1]), plain);
test('weights totalling zero give NaN, not a division by count', Number.isNaN(weightedMean(scores, [0, 0, 0])), true);
test('the result always sits between the smallest and largest value', [weightedMean(scores, percent) >= 62, weightedMean(scores, percent) <= 88], [true, true]);
The divisor is the sum of the weights, not the number of items. Get that right and normalisation stops mattering: 10:30:60, 0.1:0.3:0.6 and 1:3:6 are the same weighting, and all three give 78.9. Get it wrong and you produce 7890, which at least announces itself.
Keep weights as whole numbers when you can. 0.1 * 75 + 0.3 * 62 + 0.6 * 88 is 78.89999999999999, because 0.1, 0.3 and 0.6 are all approximations and their products drift; (10 * 75 + 30 * 62 + 60 * 88) / 100 keeps an exact integer numerator and rounds once, landing on 78.9. The difference is one bit, and one bit is enough to fail a === 78.9 check, print 78.89999999999999 on a transcript, or round down to a lower grade band. The gap of 3.9 in the fifth assertion shows the same thing from the other side: subtracting two values that are each nearest-double gives 3.9000000000000057, not 3.9.
Common mistakes
- Dividing by the count instead of the weight total. With weights of 10, 30 and 60 you get 2630 instead of 78.9.
- Writing weights as decimals and comparing with
===. 0.1, 0.3 and 0.6 give 78.89999999999999, which is not equal to 78.9. Use whole numbers, or round before comparing. - Mismatched arrays. If
wsis shorter thanxs,ws[i]isundefinedand the result isNaN. Check that both arrays have the same length.
Try it yourself
- A shop has ratings of 4.5 from 200 buyers and 3.0 from 50 buyers. Use
weightedMeanto find the overall rating. - Add a check that throws an
Errorwhenxsandwshave different lengths. - Round the decimal-weights result to one decimal place with
Math.round(x * 10) / 10and check that it now equals 78.9.