Languages
[Edit]
EN

JavaScript - weighted arithmetic mean

10 points
Created by:
Mariam-Barron
781

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

 

See also

  1. JavaScript - average value calculation

  2. JavaScript - average value calculation using array reduce()

  3. JavaScript - moving average

References

  1. Weighted arithmetic mean - Wikipedia

Alternative titles

  1. JavaScript - weighted arithmetic average
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join