1

I am trying to get an object as output using JavaScript reduce function. It's working, if I define an object {ageTotal: 0} as the second argument. How can I implement this sum of age without defining a second argument property only using an empty object {}.

const users = [
  { name: 'Tyler', age: 28},
  { name: 'Mikenzi', age: 26},
  { name: 'Blaine', age: 30 }
];

// output as a *int*
const sumAge = users.reduce((totals, current) => {
  return totals + current.age;
}, 0);
console.log(sumAge);

// output as *object*
function getUserData (users) {
  return users.reduce((data, user) => {
    data.ageTotal += user.age
    return data;
  }, { ageTotal: 0 });
}
console.log(getUserData(users));
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Mamunur Rashid
  • 1,095
  • 17
  • 28
  • I'm afraid I'm having trouble understanding the question. What result do you want? What's the problem you're having getting that result? Or what do you want to change about the code? – T.J. Crowder Jun 10 '20 at 14:44
  • If you read my post, I hope you will get it. The title is a bit confusing. – Mamunur Rashid Jun 10 '20 at 14:58
  • 1
    You can use the same code as `sumAge`. Instead of returning the int, return an object with that as a property: `const getUserData = users => ({ ageTotal: users.reduce((totals, current) => totals + current.age, 0) })` – adiga Jun 10 '20 at 15:08
  • @MamunurRashid - I read your post before posting the comment. Twice, in fact. You really shouldn't assume people haven't read your post. – T.J. Crowder Jun 10 '20 at 16:54

1 Answers1

1

You may use short-circuit evaluation while incrementing to add current age value to accumulator property ageTotal (if it exists, or set it to 0, otherwise):

data.ageTotal = (data.ageTotal || 0) + user.age

Following is a quick demo:

const users = [
  { name: 'Tyler', age: 28},
  { name: 'Mikenzi', age: 26},
  { name: 'Blaine', age: 30 }
];

// output as *object*
function getUserData (users) {
  return users.reduce((data, user) => {
    data.ageTotal = (data.ageTotal || 0) + user.age
    return data;
  }, {});
}
console.log(getUserData(users));

Or, if you seek to make your syntax more concise:

const users = [
  { name: 'Tyler', age: 28},
  { name: 'Mikenzi', age: 26},
  { name: 'Blaine', age: 30 }
];

// output as *object*
const getUserData = users =>
  users.reduce((data, {age}) => 
    (data.ageTotal = (data.ageTotal || 0) + age, data), {});

console.log(getUserData(users));
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42