How to Find the Average of an Array in JavaScript

What is an Array?

In JavaScript, an array is a data structure that allows you to store several values within a single variable. The individual values contained in the array, referred to as elements, can be of various types such as numbers, strings, or objects. Arrays are particularly useful for managing collections of data and come equipped with a wide array of built-in methods to manipulate the information they hold. Notably, the index of the first element in an array is 0.

What is the Average of an Array?

The average of an array represents the arithmetic mean of its numerical components. To calculate the average value of an array, one must first sum all the elements, and then divide that total by the number of elements present in the array. This operation is frequently performed on numerical datasets.

Using for Loop

Utilizing a for loop represents the simplest approach to determine the average of an array in JavaScript. By iterating through the array, one can accumulate the values and subsequently divide the total by the quantity of elements present.

Code:

Example

function findAverageUsingForLoop(array) {
    let sum = 0;
    for (let k = 0; k < array.length; k++) {
      sum += array[k];
    }
    return sum / array.length;
  }
  
  const numbers = [10, 20, 30, 40, 50];
  console.log("Average of Number is", findAverageUsingForLoop(numbers));

Output:

Output

Average of Number is 30

Explanation:

  • Set sum to 0 and index k to 0 .
  • Write for loop that continues to add each element to sum as long as the value of k is smaller than the length of the array.
  • Increase k with every loop.
  • Calculate the average by dividing the sum by the array length.
  • Using a while Loop

The mean can alternatively be computed by employing a while loop that includes a condition to traverse the array while manually incrementing an index.

Code:

Example

function findAverageUsingWhileLoop(array) {
    let sum = 0;
    let k = 0;
    while (k< array.length) {
      sum += array[k];
      k++;
    }
    return sum / array.length;
  }
  
  const numbers = [10, 20, 30, 40, 50];
  
  console.log("Average of Number is", findAverageUsingWhileLoop(numbers));

Output:

Output

Average of Number is 30

Explanation:

  • Set sum = 0 and an index k = 0 .
  • Use a while loop to continue adding each element to sum until k is equal to array length.
  • Increment k at each iteration.
  • Average = Sum/Length of Array.
  • Using the reduce Method

An integrated array method designed to streamline tasks like calculating the sum of all elements. The first parameter it accepts is a callback function, accompanied by an initial accumulator value.

Code:

Example

function findAverageUsingReduce(array) {
    const sum = array.reduce(
      (accumulator, currentValue) => accumulator + currentValue,
      0
    );
    return sum / array.length;
  }
  
  const numbers = [10, 20, 30, 40, 50, 100];
  
  console.log("Average of Number is", findAverageUsingReduce(numbers));

Output:

Output

Average of Number is 41.666666666666664

Explanation:

  • Here, the reduce method iterates through every element of the array and adds it to the accumulator.
  • This is the initial value of the accumulator (0).
  • Then, once sum has been calculated, divide the total sum result by the size of the array, which gives you your average.
  • Using the forEach Method

The forEach function executes a specified callback for every item within an array. Additionally, it is possible to calculate the total of numbers contained in an array using this method.

Code:

Example

function findAverageUsingForEach(array) {
    let sum = 0;
    array.forEach((element) => {
      sum += element;
    });
    return sum / array.length;
  }
  
  const numbers = [10, 20, 30, 40, 50, 70, 80, 90, 100];
  
  console.log("Average of Number is", findAverageUsingForEach(numbers));

Output:

Output

Average of Number is 54.44444444444444

Explanation:

  • Initialize a sum variable to 0.
  • Similar to the above, utilize the forEach method to go through the array and add the values to sum.
  • Iterate the total of final and divide that by the length of the array to find the average.
  • Advantages:

  • Flexibility: There are different methods available in JavaScript (such as loops and built-in methods) to calculate the average on the basis of various coding styles and requirements.
  • Readability: The functions like reduce and forEach offer concise and readable code, but only if one is experienced.
  • Reusability: Functions for computing averages can easily be reused in other contexts.
  • Efficiency: Native array methods such as reduce are optimized for performance in nearly all modern JavaScript engines.
  • Disadvantages:

  • Complexity for Beginners: Built-in methods like reduce probably seem complicated to newbies than for loops.
  • Error Handling: If the array is not strictly numeric then further checks need to be in place to prevent an error.
  • Performance in Large Arrays: These methods are fast but averaging numbers in huge arrays still matters performance.
  • Extra Code for Edge Cases: When an array is empty or contains bad values, it needs some additional logic to avoid runtime exceptions.
  • Frequently Asked Questions (FAQs)

  1. What occurs when the array is devoid of elements?

When dealing with an empty array, attempting to divide by its length (which is 0) will result in a division-by-zero error or may yield NaN (Not a Number). To prevent this issue, it is essential to verify whether the array is empty prior to proceeding with the average calculation.

  1. Is it feasible to compute the average of an array that contains non-numeric values?

It is not possible to compute the average directly if the elements within the array are non-numeric. In such cases, you either need to filter the values according to specific criteria or implement logic to handle them differently by converting them to numeric format prior to summing them.

  1. What is the quickest method for determining the average?

When handling smaller arrays, the performance variations between while loops and reduce loops are minimal. However, when it comes to larger arrays, the reduce method is typically more efficient within contemporary JavaScript engines. It is advisable to evaluate your specific scenario.

  1. What are the advantages of using reduce or forEach compared to traditional loops?

If you seek a more advanced method for managing your code, consider utilizing reduce or forEach. It is advisable to employ these techniques when you have a solid understanding of array methods in JavaScript.

  1. What strategies can I implement to manage arrays that contain missing or erroneous data?

In cases where there is a combination of invalid or non-numeric entries, it is essential to utilize functions such as filter to eliminate these values prior to executing any calculations. For instance, employing array.filter(Number.isFinite) guarantees that only valid numeric entries are preserved within the array.

  1. Can you compute the average for a multidimensional array?

Indeed, it is necessary to flatten the array utilizing either the flat method or through a recursive approach. After the array has been flattened, you can apply the same techniques as previously mentioned to compute the average.

  1. What is the best practice for managing extensive arrays?

Strive to optimize your code to its fullest potential and avoid unnecessary iterations when working with large arrays. Nonetheless, it is advisable to conduct tests, particularly when handling exceptionally large datasets. Employing built-in functions like reduce often proves to be an efficient approach.

Conclusion:

Each of these techniques presents additional examples illustrating how JavaScript enables straightforward and adaptable manipulation of arrays, facilitating common operations like this one. Thanks to the functionality provided by forEach, it accommodates all preferences, whether you favor conventional looping structures or a more contemporary array design approach.

Input Required

This code uses input(). Please provide values below: