How to Calculate in Javascript Average? | 3 Methods

One of the essential concepts in data handling is the “average.” Whether you’re a beginner or an experienced developer, understanding the intricacies of calculating averages in JavaScript is crucial.

In this comprehensive guide, we will explore the concept of the JavaScript average, its applications, and various methods to calculate it efficiently.

What is Javascript Average?

The JavaScript average refers to the arithmetic mean of a set of numbers or values.

It represents the central value that provides a general idea of the dataset.

The average serves as a valuable statistical tool for data analysis and plays a significant role in various applications across diverse domains.

How to calculate average in javascript?

To calculate the average of a dataset in JavaScript, follow these simple steps:

  1. Summing the Numbers

    Begin by adding all the values in the dataset together. The sum represents the total value of all the elements.

  2. Determining the Number Values

    Then count the total number of values in the dataset. This number will be used to divide the sum in the next step.

  3. Divide the Sum with the Count

    Divide the sum obtained in Step 1 by the count of values in Step 2. Finally, the result is the average.

Common Methods to Calculate the Javascript Average

JavaScript offers multiple approaches to calculate averages based on the data’s complexity and format. Some commonly used methods include:

1. Simple Average

The simple average is calculated by adding all the values and dividing by the count, as explained earlier.

It is suitable for datasets with a small number of element

// Function to calculate the simple average
function calculateSimpleAverage(numbers) {
  if (!Array.isArray(numbers) || numbers.length === 0) {
    throw new Error('Invalid input. Please provide a non-empty array of numbers.');
  }

  let sum = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (typeof numbers[i] !== 'number') {
      throw new Error('Invalid input. All elements in the array should be numbers.');
    }
    sum += numbers[i];
  }

  return sum / numbers.length;
}

// Example usage:
const data = [80, 90, 95, 98, 90];
try {
  const average = calculateSimpleAverage(data);
  console.log('The simple average is:', average);
} catch (error) {
  console.error('Error:', error.message);
}

Output:

The simple average is:
 90.6

In this program, we define a function called calculateSimpleAverage that takes an array of numbers as input and returns the simple average. The function first performs some basic input validation to ensure that the input is valid.

2. Weighted Average

In a weighted average, each value is assigned a weight that corresponds to its significance in the dataset. The weighted average provides a more accurate representation when some values carry more importance than others.

For example:

We will calculate the weighted average of two arrays: one array containing the values, and another array containing their corresponding weights.

// Function to calculate the weighted average
function calculateWeightedAverage(values, weights) {
  if (!Array.isArray(values) || !Array.isArray(weights) || values.length === 0 || weights.length === 0) {
    throw new Error('Invalid input. Please provide non-empty arrays of values and weights.');
  }

  if (values.length !== weights.length) {
    throw new Error('Invalid input. The number of values should be equal to the number of weights.');
  }

  let weightedSum = 0;
  let totalWeight = 0;

  for (let i = 0; i < values.length; i++) {
    if (typeof values[i] !== 'number' || typeof weights[i] !== 'number' || weights[i] < 0) {
      throw new Error('Invalid input. All elements in the value and weight arrays should be non-negative numbers.');
    }

    weightedSum += values[i] * weights[i];
    totalWeight += weights[i];
  }

  return weightedSum / totalWeight;
}

// Example usage:
const values = [80, 90, 75];
const weights = [0.3, 0.5, 0.2];

try {
  const weightedAverage = calculateWeightedAverage(values, weights);
  console.log('The weighted average is:', weightedAverage);
} catch (error) {
  console.error('Error:', error.message);
}

Output:

The weighted average is:
 84

3. Exponential Moving Average (EMA)

EMA gives more weight to recent data points, making it useful for analyzing trends and smoothing out noisy datasets.

Here is the example program:

function calculateEMA(data, smoothingFactor) {
  if (!Array.isArray(data) || data.length === 0) {
    throw new Error('Invalid input. Please provide a non-empty array of data points.');
  }

  if (typeof smoothingFactor !== 'number' || smoothingFactor <= 0 || smoothingFactor >= 1) {
    throw new Error('Invalid input. Smoothing factor should be a number between 0 and 1 (exclusive).');
  }

  let ema = data[0]; // Initialize EMA with the first data point

  for (let i = 1; i < data.length; i++) {
    if (typeof data[i] !== 'number') {
      throw new Error('Invalid input. All elements in the data array should be numbers.');
    }

    ema = (data[i] * smoothingFactor) + (ema * (1 - smoothingFactor));
  }

  return ema;
}

// Example usage:
const dataPoints = [10, 12, 15, 14, 18, 20];
const smoothingFactor = 0.2;

try {
  const ema = calculateEMA(dataPoints, smoothingFactor);
  console.log('The Exponential Moving Average (EMA) is:', ema);
} catch (error) {
  console.error('Error:', error.message);
}

Output:

The Exponential Moving Average (EMA) is:
14.467840000000002

4. Trimmed Mean

The trimmed mean involves removing outliers from the dataset before calculating the average. It is useful when extreme values may skew the results.

For example:

// Function to calculate the trimmed mean
function calculateTrimmedMean(data, trimPercentage) {
  if (!Array.isArray(data) || data.length === 0) {
    throw new Error('Invalid input. Please provide a non-empty array of numbers.');
  }

  if (typeof trimPercentage !== 'number' || trimPercentage <= 0 || trimPercentage >= 50) {
    throw new Error('Invalid input. Trim percentage should be a number between 0 and 50 (exclusive).');
  }

  // Sort the data in ascending order
  const sortedData = data.slice().sort((a, b) => a - b);

  // Calculate the number of elements to remove from both ends
  const trimCount = Math.round(sortedData.length * (trimPercentage / 100));

  // Remove the specified number of elements from both ends
  const trimmedData = sortedData.slice(trimCount, sortedData.length - trimCount);

  // Calculate the sum of the trimmed data
  const sum = trimmedData.reduce((acc, value) => acc + value, 0);

  // Calculate the trimmed mean
  const trimmedMean = sum / trimmedData.length;
  return trimmedMean;
}

// Example usage:
const dataSet = [10, 15, 20, 25, 30, 200, 35, 40, 45, 50];
const trimPercentage = 20;

try {
  const trimmedMean = calculateTrimmedMean(dataSet, trimPercentage);
  console.log('The trimmed mean is:', trimmedMean);
} catch (error) {
  console.error('Error:', error.message);
}

Output:

The trimmed mean is:
32.5

In this program, we define a function called calculateTrimmedMean that takes two inputs: data, which is an array of numbers, and trimPercentage, which is a number between 0 and 50 (exclusive) representing the percentage of outliers to be removed from both ends of the dataset.

Applications of the Javascript Average

The JavaScript average is a versatile concept and finds applications in various fields. Let’s explore some of its practical applications:

Data Analysis in Finance

In the financial sector, calculating averages is crucial for analyzing stock prices, determining investment returns, and assessing risk.

Performance Evaluation in Sports

Sports analysts often use averages to evaluate player performance, such as batting averages in cricket or shooting percentages in basketball.

Academic Grading and Assessment

Educational institutions use averages to assess student performance, calculate final grades, and identify academic trends.

Temperature Analysis in Meteorology

Meteorologists use averages to analyze temperature patterns over time, helping predict climate changes and weather conditions.

Market Research and Surveys

Market researchers employ averages to interpret survey data, gauge customer satisfaction, and derive insights for business decisions.

Nevertheless, here are other functions you can learn to enhance your JavaScript skills.

Conclusion

In conclusion, JavaScript average is a fundamental concept in data manipulation that holds significant importance across various industries. By mastering the methods to calculate averages and understanding their applications, developers can gain valuable insights from datasets and make informed decisions. Whether you’re analyzing financial data, evaluating sports performance, or conducting market research, the average is a powerful tool in your data manipulation arsenal.

Leave a Comment