Open In App

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

Last Updated : 03 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

Here are some common approaches:

Using foreach() loop

  • Iterate the array elements using foreach() loop.
  • Store the sum of each element in a variable.
  • The average of all elements will be sum/length where length is the size of the given array.

Example:


Output
4.6

Using for loop with ParseInt() method

  • Iterate the  numbers of the array using for loop
  • Use  ParseInt() function to parse the numbers in decimal format.
  • Store the sum of numbers in a variable.
  • The average of all elements will be sum/length where length is the size of the given array.

Example:


Output
4.6

Output:

 4.6

Using reduce() function

  • In this approach, We reduce i.e replace two numbers of the array with their sum in the original array.
  • reduce() function returns a single value i.e the sum of all the numbers of the array.
  • Store the return value in a variable (sum variable used).
  • The average of all elements will be sum/length where length is the size of the given array.

Example:


Output
2.5

Using for…of Loop

In this approach, we iterate over each element in the array using the for…of loop to calculate the sum of the elements, and then compute the average.

  • We initialize a variable sum to 0 to keep track of the sum of the array elements.
  • The for…of loop is used to iterate over each element in the array. For each iteration, we add the current element’s value to the sum.
  • After iterating through all elements, we calculate the average by dividing the sum by the length of the array.

Example:


Output
5.5


Next Article

Similar Reads