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 Nested Data and Additional Exploration

Begana Choi
PLUS
Begana Choi
Courses Plus Student 13,126 Points

what is the difference between those two codes?

const books = users .map(user => user.favoriteBooks.map(book=> book.title)) .reduce((books, title) => books.concat(title), []);

const books = users .map(user => user.favoriteBooks) .map(book=> book.title) .reduce((books, title) => books.concat(title), []);

in my head both codes are logical but when I run the code, the second doesn't work.

1 Answer

Steven Parker
Steven Parker
231,275 Points

In the first example, the 2nd "map" is applied to a single "favoriteBooks" array.

But in the 2nd example, the 2nd "map" is being applied to an array of "favoriteBooks" arrays, which would not have a "title" attribute.

Begana Choi
Begana Choi
Courses Plus Student 13,126 Points

sorry, I'm still a bit confused. so in the 2nd example, it doesn't have title attibute but only "favoriteBooks" arrays? but in my head, "favoriteBooks" array has title property automatically.

Steven Parker
Steven Parker
231,275 Points

Look at what gets passed on to the 2nd "map" in each example:
:white_check_mark: users.map(user => user.favoriteBooks   >>-one book array-->   .map(book => book.title))...
:x: users.map(user => user.favoriteBooks)   >>-an array of all book arrays-->   .map(book => book.title)...

In case 1, each item of the array passed to the 2nd "map" is a book object, so it easily gets the title. But in case 2, each item is an array of books, and the array itself has no "title" attribute.

If that doesn't clear it up, you might try building an running some tests where you log out just what the 2nd "map" will get and see the difference first-hand.

Begana Choi
Begana Choi
Courses Plus Student 13,126 Points

Thank you so much for an easier explanation!! :D I understand now!