Find the Longest Word in a String with .map()

Hey all! I just started the algorithm challenges. I’ve been checking my work against others, and for this one it seems I might be doing something wrong, even though I got it to work.

Spoiler alert!

This is what I got:

function findLongestWord(str) {
  var answer = 0;
  str.split(" ").map(function(x) {
    if (x.length > answer) {
      answer = x.length;
  return answer;

The two camper solutions I saw that used .map() look nothing like mine. I can’t help but feel like I’m not using best practices. So, any tips would be greatly appreciated! :slight_smile:

Doesn’t need it since he is only using the map to change the value of var answer

Reduce function is a better choice in this situation. The .map() function is for returning a collection. Reduce function is meant to reduce a collection to a single value.

// An example for you to run in your code environment.
var singleValue = ["one", "three", "five", "longest"].reduce( function( a, b ) {
  return a.length > b.length ? a.length : b.length;
}, 0);
console.log( singleValue );

You should assign str.split(" ").map( // blah ) to a variable. See if arr contains the values you expected to see. If you think your code is behaving different than you expected it to just write little test and console.log() to check.

function findLongestWord( str ) {
  // your code
  var arr  = str.split(" ").map( //blah )
  console.log( arr );
1 Like

Thanks everyone! I decided to use .reduce() instead of .map() to make my code more concise. It also seems to be closer to best practice for a problem like this. So, here’s what I ended up with:

Spoiler alert!

function findLongestWord(str) {
  var word = str.split(' ').reduce(function(a, b) {
    return a.length > b.length ? a : b;
  }, 0);
  return word.length;

As you can see, I also opted for a ternary expression instead of an if / else statement. One of my new favorite JS goodies. So thanks for that too! :smiley: