average of an array javascript

Calculate the average of an array using Javascript

In this article, we will learn how to calculate the average of an array using javascript. The average of the array is calculated by first adding all the elements in an array and then dividing it by the array’s length.

We are calculating the average of an array using different ways

1. Using reduce

// Calculate the average of an array

const array1 = [1, 3, 5, 7];
const array2 = [1, 5];

// Method 1: Using reduce
const getAverage = (array) => {
  const sum = array.reduce((total, cur) => total + cur);
  return sum / array.length;
};

const res1 = getAverage(array1) // 4
const res2 = getAverage(array2) // 3

In the code, we will calculate the sum of an array using Array.reduce() method where we will iterate through the array and save the current value to the sum variable. 

After calculating the sum of an array, we will find the average by dividing the array sum by the length of an array. 

2. Using ForEach

// Calculate the average of an array

const array1 = [1, 3, 5, 7];
const array2 = [1, 5];

// Method 2: Using forEach
const getAverage = (array) => {
  let sum = 0;
  array.forEach((item) => {
    sum = sum + item;
  });
  return sum / array.length;
};

const res1 = getAverage(array1); // 4
const res2 = getAverage(array2); // 3

In this, we are using Array.forEach() to find the array sum. Here we have a variable named sum with an initial value of 0 and then in each iteration of forEach, we will add the current element value to the sum variable.

As discussed in the above method, we have used the same technique to calculate the average of an array.

3. For an Array of objects

// Calculate the average of an array

const array1 = [
  { user: "abc", marks: 80 },
  { user: "pqr", marks: 60 },
  { user: "xyz", marks: 40 },
];

// Method 3: For Array of objects
const getAverage = (array) => {
  const sum = array.reduce((total, item) => total + item.marks, 0);
  return sum / array.length;
};

const res1 = getAverage(array1); //60

In the previous two methods, we are calculating the array average for primitive elements. Here, we will calculate the average of the array of objects.

In the above code, we are using reduce() method to calculate the sum of the array of objects. Then we are dividing it by the array’s length to get the average.

Also, Check this

Leave a Comment

Your email address will not be published. Required fields are marked *