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");

What is a subindex and how are you wanting to compare them?

1 Like

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.

OK, so far you have created an array of words from the string passed to the array. Now you must think how you will iterate through the array and compare each word’s length and keep track of the one that is the largest. How would track this if you were doing this on paper? Think about the steps you would take.

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");

FYI The extra Math.max(...arr); line before the return statement is not needed here.

Also, you technically do not need to use arrays to solve this challenge. Think about how you could do it with only the variable named lthEchWrd.

1 Like