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));
4
  • 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? Commented Jun 10, 2020 at 14:44
  • If you read my post, I hope you will get it. The title is a bit confusing. Commented Jun 10, 2020 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) }) Commented Jun 10, 2020 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. Commented Jun 10, 2020 at 16:54

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Yevgen Gorbunkov

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.