Tell us what’s happening:
I believe the best way to learn something is to try to explain it, but I live alone with nobody to talk to, so whenever I feel like I don’t quite understand something, I somewhere to post my thoughts. I’d like to try here and see if my understanding of the problem is correct. The curriculum doesn’t really do a good job of introducing how reduce works, so I will stumble through my understanding of it after watching a couple of videos on the topic.
The first line:
return s.split(' ')
This splits the string into an array of words. I don’t think the order is maintained here, but it’s not important to the task at hand.
the second line:
.reduce (function (x, y) {
I don’t really like that whoever wrote this line used “x” and “y”, but I think x is supposed to refer to the current largest word and y refers to the next word in sequence that’s being examined. In the videos, “x” is the accumulator and I understand that this value is supposed to persist throughout the function while “y”, the current value is cycled and compared to “x” in some fashion, whether it’s added, subtracted, replaced or etc. This line, by itself, does not yet seem to instruct the function what to do between x and y. That part I think comes after.
return Math.max(x, y.length)
This line tells the function to compare between “x” and the length of “y” and choose the larger of the two elements. The code explanation tells me that the “0” at the very end of this code instructs the function where to start “x”. If the 0 isn’t there, I assume I’ll get an error because with no value to compare with “y”, Math.max has nothing to work with?
Finally, what kinds of problems will the reduce function work best with? For loops?
Your code so far
function findLongestWordLength(s) {
return s.split(' ')
.reduce(function(x, y) {
return Math.max(x, y.length)
}, 0);
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36
.
Challenge: Find the Longest Word in a String
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string