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

Reduce Method doubt.

Hi everyone! I was getting all the new method until I saw .reduce where I get some doubts. Why [user.name] = user.age ??? Why equal and why user.age is not inside of brackets?

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

3 Answers

Steven Parker
Steven Parker
229,744 Points

This reduce is being used to build a new object from the array. The "usersObj[user.name]" identifies a new property in the object using the user name as the property name. The assignment ("=") creates that new property and gives it the value of the user's age. And "user.age" has no brackets because the assignment uses the value directly and does not want to create an array.

If you look at about 7:20 in the video, you can see the example object created by running this on sample data.

Thanks a lot once again Steven! I got it. Just if you have a minute, I didn't get too much about when should I use .filter and .map, which is the difference between them exactly? I realize that I made all the challenges without watching the solution but because in the challenge said "use .filter" or "use .map" but then I realize that, that I don't get which difference are between them.

Thanks for your time and your patiences :)

Steven Parker
Steven Parker
229,744 Points

This really should be a separate question since it is unrelated, but here's a short description:

Both "filter" and "map" take a callback argument, and they pass each array element to the callback one at a time. The difference is what they do with the result.

In "filter", the callback returns a boolean value, and if the value is True, the current element is added to a new array. If False, that element is skipped. So the length of new array is up to the callback, and it will have all, some, or none of the original elements.

But in "map", whatever the callback returns is put into the new array, so the new array will always be the same length as the original (but the contents are up to the callback).

Both methods return the newly constructed array as their result.

Hi there Steven! Excellent explanation, I got it. Thanks for your time, that was the answer I need to finish understand themπŸ‘