Last active
December 27, 2023 20:16
-
-
Save petergi/d4ffba911f98683ee8ead2811a5bce08 to your computer and use it in GitHub Desktop.
Calculates the weighted average of two or more numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Calculates the weighted average of an array of numbers. | |
| * | |
| * @param {number[]} nums - The array of numbers to be averaged. | |
| * @param {number[]} weights - The array of weights corresponding to each number in `nums`. | |
| * @return {number} The weighted average of the numbers. | |
| */ | |
| const weightedAverage = (nums, weights) => { | |
| let sum = 0; | |
| let weightSum = 0; | |
| for (let i = 0; i < nums.length; i++) { | |
| sum += nums[i] * weights[i]; | |
| weightSum += weights[i]; | |
| } | |
| return sum / weightSum; | |
| }; | |
| weightedAverage([1, 2, 3], [0.6, 0.2, 0.3]); // 1.72727 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment