I have a list of users along with their ages, and I need to calculate the average age of all users. I initially attempted to use the reduce
method for this task, but encountered syntax errors preventing successful implementation.
Below is the code snippet I used:
let sam = { name: "Sam", age: 21 };
let hannah = { name: "Hannah", age: 33 };
let alex = { name: "Alex", age: 24 };
let users = [sam, hannah, alex];
function getAverageAge(array){
let sumAge = array.age.reduce(function(sum, current) {
return sum + current;
}, 0)
return (sumAge / (array.length));
}
console.log(getAverageAge(users)); // Expected output: (21 + 33 + 24) / 3 = 26
The expected result in this case should be 26.