Mamunur Rashid
Mamunur Rashid

Reputation: 1185

Get sum of property values within array of objects

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

Upvotes: 1

Views: 670

Answers (1)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

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

Upvotes: 1

Related Questions