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));