[SOLVED] Why doesn't the second code work the same as the first code?

Issue

The First Code works correctly and displays the right answer which is 19.

function findLongestWordLength(str) {
  let high = 0;
  let word = str.split(" ");
  
  for(let i = 0; i < word.length; i++)
  {
   if (word[i].length > high)
      high = word[i].length;
  }
  console.log(high)
}

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

The second code below, only works until the word "super-long" and logs 10 as the final output, which is incorrect. I’m trying to figure out what goes wrong here. It works fine with other sentences,

FOR REFERENCE

The str.length in the sentence is 60(spaces included), and there are 9 spaces in between the entire sentence


function findLongestWordLength(str) {
  let high = 0;
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] != " ") {
      count++;
    } else {
      if (count >= high)
        high = count;
      count = 0;
    }
  }
  return high;
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

Solution

In order to get 19, you have to end your string with a space. Because the last character of "otorhinolaryngology" is a 'y', you simply increment count at the very end and you never hit your else condition which will update high. Put a space at the end, add an extra condition checking if i == str.length -1 Or simply use the length algorithm, or, as I would prefer, use a reducer like so:

const findLongestWordLength = str => str.split(' ').reduce((acc, word) => word.length > acc ? word.length : acc, 0)

Answered By – Joshua Wood

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.