Basic Algorithm Scripting: Find the Longest Word in a String , chek my code

Why It does not pass the test cases

function findLongestWordLength(str) {
  let strArray = str.split('');
  let lengthArray=[];
  for(let i = 0;i<strArray.length;i++)
  {
    lengthArray.push(strArray[i].length);
  }
  lengthArray.sort();

  return lengthArray[strArray.length-1];
}

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

Hi Hiten,

I’m new here but here’s a tip for finding bugs: add console.log statements everywhere!

For example, I’ve added a line that should print each element in strArray and found that your split statement
is splitting the text into individual characters instead of splitting str into words as I assume you were trying to do.

function findLongestWordLength(str) {
    let strArray = str.split('');
    let lengthArray = [];
    for (let i = 0; i < strArray.length; i++) {
        console.log(strArray[i]); // Output: T, h, e, q, u, i, c, k, b, r, o, w, n, f, o, x, j, u, m, p, e, d, o, v, e, r, t, h, e, f, e, n, c, e
        lengthArray.push(strArray[i].length);
    }
    lengthArray.sort();

    return lengthArray[strArray.length - 1];
}

A simple fix to your code would be to split str by a space character instead:
i.e.

let strArray = str.split(' ');

@JoelLau tahnks buddy:grinning:

You probably wanna take a look to the Math.max() function to help you with this challenge. Also something that I find really helpful when solving these challenges is to write a pseudo code, like a serie of steps that you should follow to solve the challenge.

That’s how I found out about the function I mentioned before. I wrote the steps that I thought I had to follow to solve the problem, then if I didn’t know how to do a certain step, I googled my question. And as suggested above, console.log everything. I personally use jsfiddle whenever I’m doing a challenge.

1 Like