How to use for…of Loop In Javascript
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:
// Define the array
let arr = [5, 7, 2, 7, 8, 3, 9, 3];
// Function to calculate the average using for...of loop
function avg(arr) {
let sum = 0;
// Iterate over the elements of the array
for (let value of arr) {
sum += value;
}
// Calculate the average
return sum / arr.length;
}
// Call the function and log the output
console.log(avg(arr));
Output
5.5
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