Basic Algorithm Scripting: Find the Longest Word in a String*


I want to compare every subindex.

function findLongestWordLength(str) {
  let words=str.split(" ");
  console.log(words)
  return str.length;
}

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

I want to compare every element in a array in order to get the highst number. That would be my longest word. The subindex is every position in an array.

I would iterate twice through them and I would make a comparation. I think I would need to do the comparation with a method.

function findLongestWordLength(str) {
  let words=str.split(" ");
       
       for(let i=0;i<words.length;i++) {


             for(let j=0;j<words[i].length;j++){
                        

                        if (j==words[i][j].length){

                               return j; 
                                    
                        }
                                     
                      
             }
       }


  return str.length;
}

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

There is no need to iterate through twice.

What is your algorithm to solve the problem if you had to do this with pen and paper (no JavaScript)? Try to describe your steps.

3 Likes

Algorithm: 1.-To separate the whole string into words. 2.-To count characters in each of them. 3-to Compare the total of every word. 4- To get the highest one.

Thanks! I am grateful for your time.

function findLongestWordLength(str) {
  let words=str.split(" ");
   
   let arr=[];
   let lthEchWrd=0;
      
       for(let i=0;i<words.length;i++) {

          let lthEchWrd  =words[i].length;

          //let longestWrd =Math.max(arr)                      
               arr.push(lthEchWrd)
             }
            
           Math.max(...arr);   
          


  return   Math.max(...arr);
}

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