Development

JavaScript Average Function

Captain Salem 4 min read

JavaScript Average Function

JavaScript is an incredible programming language for the modern age. It enables us to create complex web and mobile applications using a single language. Due to its popularity and ease of use, you will often find it as your choice for your work.

An example is learning how to use JavaScript in your mathematical operations. In this tutorial, you will learn how to calculate the average or the arithmetic mean of a given set of values in an array.

Let us dive in.

Custom JavaScript Function

The first method we can use is defining a custom average function. This is easy if we break down the logic of the mathematical average in simple steps.

Let us see how to do this in pseudo-code.

  1. Calculating the average is simply taking the total sum of elements present, then dividing it by the total number of values present in an array.
  2. Take, for example, an array => [1,2,3,4,5]
  3. From the array above, we can see that the total number of elements in the array = 5
  4. Using a mathematical average, we can start by getting the sum of all elements in the array: 1 + 2 + 3 + 4 + 5 = 15
  5. Hence, to get the average of the array, we need to take the sum of all values in the array, divided by the number of elements in the array. 15/5 = 3

Now that we know how to do this without code, let us go back and use JavaScript to implement a function that does the above.

  1. We will start by defining a function that takes an array as an argument.
  2. We will then define a variable to hold the sum of elements and set its value to equal 0.
  3. We will then use a loop to iterate over each array element and add its value to the sum variable. Once iteration, JavaScript will add the array value to the available sum.
  4. Finally, the function will return the sum divided by the array’s length. That should be equal to the average.

An example code is as shown below:

function avg(array) {
letfunction avg(array) {
    let sum = 0;
    for (let i = 0; i < array.length; i++) {
        sum += array[i];
    }
    return sum / array.length
}
console.log(avg([1,2,3,4,5]))
}

Once we run the code above, we should get the average of all values in the array as shown:

image-20221227104641519
image-20221227104641519

Method 2 - JavaScript Get Average Function Using the Reduce() Method.

The reduce() function is a method of the Array object in JavaScript that applies a function to each element in the array, resulting in a single output value. The function takes two arguments: a “reducer” function and an initial value for the reduction.

The reducer function is applied to each element in the array, starting from the left. It takes two arguments: an “accumulator” value, which is the result of the reduction so far, and the current element being processed. The reducer function returns a new accumulator value passed to the next iteration of the function.

The initial value for the reduction is optional. If it is not provided, the first element of the array is used as the initial value, and the reducer function is applied to the remaining elements of the array.

Consider a test example shown below:

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);

Output:

output:
15

In this example, the reducer function is a lambda function that takes the accumulator and the current element as arguments and returns the sum of those two values. The initial value for the reduction is 0. The reduce() function starts by setting the accumulator to 0 and then applying the reducer function to each element in the array, starting from the left.

By now, you have already figured out how we can use the reduce() function to get the average of the values in an array.

Take the code below:

function average(array) {
    return array.reduce((x,y) => x+y)/array.length
}

console.log(average([1,2,3,4,5]))

Where x represents the accumulator and y represents the current value. Running the code above should return:

output:
3

Method 3 - JavaScript Get Average using the forEach Function

We can also use the JavaScript forEach() function to get the average of values in a given array. Let us see how this works.

The forEach() function is a method of the Array object in JavaScript that executes a provided function once for each array element. The function takes three arguments: the current element being processed, the index of the element, and the array itself.

Example:

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(element, index, array) {
  console.log(element);
});

Output:

1,2,3,4,5

Since the forEach() function works as an iterator, we can use it to calculate the average of the values of the array, as shown in the code below:

function average(array) {
  sum = 0;
  array.forEach((element) => {
    sum += element;
  });
  return sum / array.length;
}
console.log(average([1,2,3,4,5]))

Output:

3

It is also worth noting that the forEach() function does not return a value. This makes it unsuitable in cases where a return value is necessary. Consider other functions such as map() or reduce() functions in such cases.

Conclusion

In this post, you learned various methods and techniques you can use to calculate the average of elements in a given array in JavaScript.

We hope you enjoyed this post && Thank you for reading.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.