Average with the Reduce Method in JavaScript


In the given problem statement, our aim is to get the average of all the items with the help of the reduce method of Javascript. So for doing this task we will create a function and give an array as a parameter.

Understanding the problem statement

We have given a task to calculate the average value of the given items in the array. And we have to use the reduce method which is a predefined method of Javascript. For example if we have an array as [1, 2, 3, 4, 5], so the average value of the items for this array will be 3. (1 + 2 + 3 + 4 + 5) / 5 = 15 / 5 = 3.

Logic for the given problem

As we have to use the reduce method in Javascript. So first we will create a function which will take an argument of an array as input. Inside the function we will check that the array is empty or not. If it is empty then the function should return zero otherwise we will use the reduce method for the array to calculate the sum of all the elements. And we will divide the sum with the length of the array to get the average value.

Algorithm

Step 1: Declare a function to get the average of all the items or numbers present in the array and assign it a name as getAverage.

Step 2: Check if-else condition that the array is empty. If it is empty then return zero because we don't have any items in the array.

Step 3: Otherwise, with the help of the reduce method we will calculate the sum of all the items present in the array. And set the initial value of the accumulator to zero.

Step 4: Divide the calculated sum with the length of the array to get the average of the elements.

Step 5: At the end return the average value of the items.

Example

//function to get the average of elements
function getAverage(arr) {
   if (arr.length === 0) {
     return 0;
   }
   
   const sum = arr.reduce((acc, curr) => acc + curr, 0);
   const average = sum / arr.length;
   return average;
  }
 
const numbers = [1, 2, 2, 3, 4, 4, 5, 5];
const avg = getAverage(numbers);
console.log("Average is : ",avg);

Output

Average is :  3.25

Complexity

The time taken by the defined algorithm is O(n) if n is the size of the input array. The reason for this complexity is, as we are using the reduce method which iterates every element of the array one time to calculate the sum.

Conclusion

In the above code we have used reduce method which is a powerful method in Javascript for doing calculations on arrays. It is very useful to calculate the average of an array by getting the sum of all the items and dividing it by the length of the array. This is the efficient way with a linear time complexity and suitable for large size arrays.

Updated on: 11-Aug-2023

583 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements