freeCodeCamp Challenge Guide: Find the Longest Word in a String

Here’s a solution from a sadomasochistic point of view:

  1. Split the sentence string into “individual” words so you can str.length your way into each one of them. The .split() method will create an array of words you can work with.

  2. Create a placeholder to store the length of the longest element in the array.

  3. Fire up an iteration that will cycle through each element of the array. Compare each element’s length vs. the length stored in the placeholder. If the length of the element in question is greater than the current value in the placeholder, then let the length of that element be the new value of the placeholder.

  4. At the end of the iteration, return with the value of the placeholder.

let newArr = str.split(" ");
let longest = 0;
console.log(longest);
for (i = 1; i < newArr.length; i++) {
if (newArr[i].length > longest) {
longest = newArr[i].length;
};
}
return longest;