JavaScript JavaScript Array Iteration Methods Combining Array Methods Nested Data and Additional Exploration

Begana Choi
PLUS
Begana Choi
Courses Plus Student 13,122 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
207,988 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,122 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
207,988 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,122 Points

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