0

I am trying to call this reduce function:

users.reduce(function (acc, obj) { return acc + obj.age/3; }, 0);   

in this function:

function computeUserAverageAge(users) {};

to test this array of objects for the average of these "age" values:

const users = [{
           name: 'Brendan Eich',
           age: 56,
         }, {
           name: 'Linus Torvalds',
           age: 48,
         }, {
           name: 'Margaret Hamilton',
           age: 81,
         }];

I am thankful for your help and patience!

  • Possible duplicate of [Calculating the average of object properties in array](https://stackoverflow.com/questions/25930547/calculating-the-average-of-object-properties-in-array) – Heretic Monkey Jun 09 '18 at 23:31

2 Answers2

2

Just move it with in the function and return the result.

Note: instead of using 3 use users.length instead.

I also think that mathematically, you should divide by the number after you add them up, and not each iteration.

const users = [{
  name: 'Brendan Eich',
  age: 56,
}, {
  name: 'Linus Torvalds',
  age: 48,
}, {
  name: 'Margaret Hamilton',
  age: 81,
}];

function computeUserAverageAge(users) {
  return Math.round(users.reduce((acc, obj) => acc + obj.age, 0) / users.length);
};

console.log(computeUserAverageAge(users))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Thanks, and if I wanted to round the answer I could put: function computeUserAverageAge(users) { return Math.floor(users.reduce(function(acc, obj) { return acc + obj.age / users.length; }, 0);) }; ? – Jordan Merrill Jun 09 '18 at 22:53
  • 1
    use `Math.round()`, `Math.floor()` or `Math.ceil()`, see my above edits. – Get Off My Lawn Jun 09 '18 at 22:54
0

Sounds like you just need to return the result of the reduce. Might as well use arrow functions for brevity:

const computeUserAverageAge = users => users.reduce((a, { age }) => a + age, 0) / 3;
console.log(computeUserAverageAge(
  [{
    name: 'Brendan Eich',
    age: 56,
  }, {
    name: 'Linus Torvalds',
    age: 48,
  }, {
    name: 'Margaret Hamilton',
    age: 81,
  }]
));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320