Introduction
In this lab, we will explore how to calculate the weighted average of two or more numbers using JavaScript. We will be using the Array.prototype.reduce() method to create the weighted sum of the values and the sum of the weights, and then divide them with each other to get the weighted average. This lab will help you understand the concept of a weighted average and how to implement it in JavaScript.
How to Calculate Weighted Average in JavaScript
To calculate the weighted average of two or more numbers in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduce()to create the weighted sum of the values and the sum of the weights. - Divide the weighted sum of the values by the sum of the weights to get the weighted average.
Here's the JavaScript code for the weightedAverage function:
const weightedAverage = (nums, weights) => {
const [sum, weightSum] = weights.reduce(
(acc, w, i) => {
acc[0] = acc[0] + nums[i] * w;
acc[1] = acc[1] + w;
return acc;
},
[0, 0]
);
return sum / weightSum;
};
You can use the weightedAverage function to calculate the weighted average of an array of numbers and an array of weights like this:
weightedAverage([1, 2, 3], [0.6, 0.2, 0.3]); // 1.72727
Summary
Congratulations! You have completed the Weighted Average lab. You can practice more labs in LabEx to improve your skills.