Find the Longest Word in a String.?

I’m stuck in part and Maybe I’m missing something or I’m totally wrong but I can’t figure out what is wrong in my syntax.Can you help me?


function findLongestWord(str) {

var a = str.split(" ");
var y = [];
y.push(a);
var con = “”;

for(var i =0;i<y.length;i++){

 if(y[0][i].length>y[0][i+1].length){
  con = y[0][i];

}

else if(y[0][i].length<y[0][i+1].length){
  con = y[0][i+1];
}
 

else if(y[0][i].length>y[0][i-1].length){
  
  con = y[0][i];
  
}
else if(y[0][i-1].length>y[0][i].length){
  
  con = y[0][i-1];
  
}
else {
  
 con = y[0][i];
  
}

}
return con.length;
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

First of all, your 2nd and 3rd lines y.push(a); and y.push(a); are redundant; you’re basically taking the empty array y and pushing all of array a onto it. Just use your array a.

Secondly, you’ve got way too many else statements which is super confusing.
Here’s my solution, which is probably not ideal, but works on the same principles as yours, with much more brevity:

My solution:
function findLongestWord(str) {

var strArray = str.split(" ");
var newLength = 0;
var eachWord; 

for ( var i = 0; i < strArray.length; i ++ ) {
  eachWord = strArray[i].length;
    if ( eachWord > newLength ) {
      newLength = eachWord;
    }
}
  
  return newLength;
}

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

Also, may I recommend you use some spacing in your code - it’s hard to read.
For example:

  for ( var i =0; i < y.length; i++ ) {

  if ( y[0][i].length > y[0][i+1].length ) {

etc...

This is recommended by various advanced programmers. Your code should be easy to read.

Thanks bro… It does work so well:) I will be careful when I post.It is my first post in this forum

1 Like

You’re welcome. I’m fairly new myself.