-2

I have an array of users with ages, I want to get the average age of users. So far I tried to do it with reduce but it won't implement it's not the right syntax for reduce.

Here is my code:

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 + 1));
}

console.log( getAverageAge(users) ); // 21 + 33 + 24 / 3 = 26

In this case, it should return 26.

Robert Hovhannisyan
  • 2,938
  • 6
  • 21
  • 43

1 Answers1

2

Arrays don't have a age property it is your object that has it:

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){
  const sumAge = array.reduce(function(sum, current) {
    return sum + current.age;
  }, 0)

  return (sumAge / array.length);
}

console.log( getAverageAge(users) );
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44