How to compute the average of an array after mapping each element to a value in JavaScript ?
Last Updated :
22 Jul, 2021
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:
- 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.
Index.js
Javascript
<script>
arr = [2, 3, 5, 6, 7];
function avg(arr) {
var sum = 0;
arr.forEach( function (item, idx) {
sum += item;
});
return sum / arr.length;
}
console.log(avg(arr));
</script>
|
Output:
4.6
Approach 2:
- 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.
Index.js
Javascript
<script>
arr = [2, 3, 5, 6, 7];
var sum = 0;
for ( var i = 0; i < arr.length; i++) {
sum += parseInt(arr[i], 10);
}
var avg = sum / arr.length;
console.log(avg);
</script>
|
Output:
4.6
Approach 3: 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.
Index.js
Javascript
<script>
var arr = [1, 2, 3, 4];
function check(a, b) {
return a + b;
}
var sum = arr.reduce(check);
var avg = sum / arr.length;
console.log(avg);
</script>
|
Output:
2.5
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...