How to compute the average of an array after mapping each element to a value in JavaScript ?
To compute the average of an array after mapping each element to a value in JavaScript, you can follow these steps:
- Use the
map()
method to create a new array with the mapped values. - Use the
reduce()
method to sum up all the values in the new array. - Divide the sum by the length of the new array to get the average.
Here's an example code snippet that demonstrates this approach:
const arr = [1, 2, 3, 4, 5];
// Map each element to its square
const mappedArr = arr.map(x => x * x);
// Compute the average of the mapped array
const sum = mappedArr.reduce((acc, val) => acc + val, 0);
const avg = sum / mappedArr.length;
console.log(avg); // Output: 11
Alternatively, you can use the forEach()
method to iterate over the array and compute the sum and count of the mapped values, and then divide the sum by the count to get the average. Here's an example:
const arr = [1, 2, 3, 4, 5];
// Map each element to its square
const mappedArr = arr.map(x => x * x);
// Compute the average of the mapped array
let sum = 0;
let count = 0;
mappedArr.forEach(val => {
sum += val;
count++;
});
const avg = sum / count;
console.log(avg); // Output: 11
Both of these methods will give you the same result, which is the average of the mapped array.