How to use for loop with ParseInt() method In Javascript
- 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:
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);
Output
4.6
Output:
4.6
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
Here are some common approaches:
Table of Content
- Using foreach() loop
- Using for loop with ParseInt() method
- Using reduce() function
- Using for…of Loop