Open In App

How to compute the average of an array after mapping each element to a value in JavaScript ?

Given an array, the task is to compute the average of an array after mapping each element to a value.

Input : arr=[2, 3, 5, 6, 7]
Output: 4.6
Explanation : (2+3+5+6+7)/5 = 4.6 

Input : [5,7,2,7,8,3,9,3]
Output: 5.5
Explanation : (5+7+2+7+8+3+9+3)/8 = 5.5 

Approach1:



Index.js




<script>
  arr = [2, 3, 5, 6, 7];
 
  // Function to calculate the average of numbers
  function avg(arr) {
    var sum = 0;
 
    // Iterate the elements of the array
    arr.forEach(function (item, idx) {
      sum += item;
    });
 
    // Returning the average of the numbers
    return sum / arr.length;
  }
 
  console.log(avg(arr));
</script>

Output:



4.6

Approach 2:

Index.js




<script>
  arr = [2, 3, 5, 6, 7];
  var sum = 0;
 
  // Iterating the elements of the loop
  for (var i = 0; i < arr.length; i++) {
 
    // Store the sum of all numbers
    sum += parseInt(arr[i], 10);
  }
 
  // Taking the average
  var avg = sum / arr.length;
 
  console.log(avg);
</script>

Output:

 4.6

Approach 3: Using reduce() function

Index.js




<script>
  var arr = [1, 2, 3, 4];
  // Callback function calculating
  // the sum of two numbers
  function check(a, b) {
    return a + b;
  }
   
  // Reducing the numbers of the array
  var sum = arr.reduce(check);
   
  // Calculating the average of the numbers
  var avg = sum / arr.length;
 
  console.log(avg);
</script>

Output:

2.5

Article Tags :