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 trialBegana Choi
Courses Plus Student 13,126 Pointswhat 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
231,275 PointsIn 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
Courses Plus Student 13,126 PointsBegana Choi
Courses Plus Student 13,126 Pointssorry, 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
231,275 PointsSteven Parker
231,275 PointsLook at what gets passed on to the 2nd "map" in each example:
users.map(user => user.favoriteBooks
 >>-one book array--> Â.map(book => book.title))
...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
Courses Plus Student 13,126 PointsBegana Choi
Courses Plus Student 13,126 PointsThank you so much for an easier explanation!! :D I understand now!