Find the Longest Word in a String(solved)

Tell us what’s happening:
So I actually solved it, but I clicked “get a hint” because normally there are better solutions.

In there, there is one similar to mine using reduce instead of map. I can get it and actually maybe it’s a little simpler than mine, but I don’t know, it’s mine quite good enough?

But then there is one using recursiveness. For everything in this world, I can’t ever creatively say “I will use recursivity!”, it just escapes me. Actually in this case I find it quite convulted…

Is recursivity a neccesary trait in the everyday of a coder’s life?

Your code so far


function findLongestWordLength(str) {
  let newArr = str.split(' ').map( (element) => element.length );
  return newArr.sort((a, b) => b - a)[0];
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

Your solution looks really smart to me! It’s great that you made use of map and sort.

I just finished the JavaScript certification and definitely feel your pain… recursive functions are a little mind-bending. You’ll encounter it a few more times as you work through the challenges.

Looking at the variety of solutions in the Hints page is so helpful! It’s nice to be able to compare the solutions as a way of familiarizing yourself with different tools for the same job.

1 Like

The thing about sorting is that it’s computationally expensive compared to iterating over your data. It’s not a big deal for small data sets, but when you want to optimize it’s something you try to avoid.

1 Like

Thanks, yes, I actually feel accompilshed in thinking in those functions, i know it’s quite minimum but well

Got it, so the best solution would be the reduce one?

It is in my opinion. As far as I can tell the three given solutions are all O(n), and the .reduce method is short and clear. Comparison sorts are O(n log n). If you’re not familiar with big O notation, look up a chart and you’ll see why one is preferred to the other.

I am not familiar, I will look into it, thanks!

My fav solution is a functional approach using two functions.

function1 (uppercases first letter of word)
function2 (uses function1 and applies it to each word using map)

Whoops different problem., lol…