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

Using JS map() with reduce()

I reached to this question on which I'm being asked to map items in an array of objects (first name + last name) and reduce them into one string.

This is a shortened version of the array:

let authors = [
  { firstName: "Beatrix", lastName: "Potter" },
  { firstName: "Ann", lastName: "Martin" },
];

This failed, why?

fullAuthorNames = authors.map( (e)=> 
    authors.reduce( (firstName, lastName)=> firstName + lastName );
);

Using join in the following way also didn't help (it feels to me simpler).

let fullAuthorNames = authors.map(a => a.firstName + " " + a.lastName).join(", ");

2 Answers

Steven Parker
Steven Parker
243,266 Points

I re-read the original challenge, and it doesn't say anything about "reduce them into one string". It says "create an array of full name strings".

So you don't need "reduce" or "join" here, just "map". Your first example will work after removing the "join" and also the extra spaces before and after the name.

You are right. I confused reduce() with this given it came after a video showing how to combine map() and reduce(). My bad. All the post-question videos there tend to deal directly with what the video did, so I confused it in this way.

Steven Parker
Steven Parker
243,266 Points

Here's a few possible reasons (the first two for sure):

  • there's a stray semicolon at the end of the "reduce" line
  • the object properties would need to be accessed using a reference to the object
  • I would expect to see "map" and "reduce" chained together instead of nested
  • "map" could be used to convert the objects into individual strings
  • then the "reduce" might be used to combine the individual strings into one

You have it half right (the "map" part) in the "join" version. Now just "re-invent join" using "reduce" and you'll have it.

fullAuthorNames = authors.map( (i)=> `  ${i.firstName} ${i.lastName} `).join()

This should do it but the TreeHouse API is insisting that double quotes would be around each pair, it wants it to be:

"Beatrix Potter", "Ann Martin"

But with my code it's the following, which fails:

" Beatrix Potter , Ann Martin "

Doing it this way doesn't help:

fullAuthorNames = authors.map( (i)=> `  "${i.firstName} ${i.lastName}" `).join()

Thanks Steven. I know, I just did so.