Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Array Iteration Methods Combining Array Methods Working with Objects in Arrays

andreasantecki
andreasantecki
12,577 Points

Can someone explain the .reduce method from this video please?

I understood so far the other methods used in the video and the videos before. But how does .reduce work here?

const usersObject = users
  .reduce((usersObject, user) => {usersObject[user.name] = user.age;
    return acc;
  }, {});

What is actually going on when we set: usersObject[user.name] = user.age; and why can we set another object {} and the method knows directly what to do with it?

2 Answers

Steve Gallant
Steve Gallant
14,943 Points

I had trouble with this one too...reduce() is giving me fits and seems to require a bit more of my attention than the other methods so far. This example was a great light bulb moment for me.

Unlike previous examples for reduce(), when dealing with simple numbers and setting the initial value of the accumulator to 0, in this example he sets the initial value of the accumulator (called usersObject) to an empty object {}. Now, within the function, he simply creates a new property inside the empty object that gets its name from 'user.name' from the array we started with, and sets the value of the new property to the 'user.age' value from the array. This repeats for each item in the original array, adding new properties to the usersObject object.

I think this is an accurate description of what is happening. Hope this helps you as much as it helps me to write it all out! Steve

Adam Beer
Adam Beer
11,314 Points

The reduce() executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments.