Calculating Weighted Averages in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28695{{"`Calculating Weighted Averages in JavaScript`"}} javascript/data_types -.-> lab-28695{{"`Calculating Weighted Averages in JavaScript`"}} javascript/arith_ops -.-> lab-28695{{"`Calculating Weighted Averages in JavaScript`"}} javascript/comp_ops -.-> lab-28695{{"`Calculating Weighted Averages in JavaScript`"}} javascript/array_methods -.-> lab-28695{{"`Calculating Weighted Averages in JavaScript`"}} javascript/higher_funcs -.-> lab-28695{{"`Calculating Weighted Averages in JavaScript`"}} end

How to Calculate Weighted Average in JavaScript

To calculate the weighted average of two or more numbers in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.reduce() to create the weighted sum of the values and the sum of the weights.
  3. 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.

Other JavaScript Tutorials you may like