Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,915 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,304 Points

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