Three Ways to Find the Longest Word in a String in JavaScript of Recommendation

  • 2021-10-24 18:40:18
  • OfStack

This article is based on the Free Code Camp basic algorithm script "Find the longest word in a string."

In this algorithm, we look at each word and calculate how many letters there are in each word. Then, compare the counts to determine which word has the most characters and return the length of the longest word.

In this article, I will explain three methods. The FOR loop is first used, the sort () method is second, and the reduce () method is third.

Algorithm challenge

Returns the length of the longest word in the provided sentence. Your reply should be 1 number.

Test cases provided

findLongestWord ("The quick brown fox jumped over the lazy dog") returns 1 digit findLongestWord ("The quick brown fox jumped over the lazy dog") returns 6 findLongestWord ("May the force be with you") returns 5 findLongestWord ("Google do a barrel roll") returns 6 findLongestWord ("What is the average airspeed velocity of an unladen swallow") returns 8 findLongestWord ("What if we try a super-long word such as otorhinolaryngology") returns 19

function findLongestWord(str) {
 return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

1. Use the FOR loop to find the longest word

For this solution, we will use the String. prototype. split () method

The split () method splits string objects into string arrays by splitting strings into substrings.

We will need to add a space between the parentheses of the split () method


var strSplit =  " The quick brown fox jumped over the lazy dog " .split( '   ' );

It will output an array of words:


var strSplit = [ " The " ,  " quick " ,  " brown " ,  " fox " ,  " jumped " ,  " over " ,  " the " ,  " lazy " ,  " dog " ];

If you don't add spaces in parentheses, you will get the following output:


var strSplit = 
[ " 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 " ,  "   " ,  " l " ,  " a " ,  " z " ,  " y " ,  "   " ,  " d " ,  " o " ,  " g " ];

function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
 
 // Step 2. Initiate a variable that will hold the length of the longest word
 var longestWord = 0;

 // Step 3. Create the FOR loop
 for(var i = 0; i < strSplit.length; i++){
 if(strSplit[i].length > longestWord){ // If strSplit[i].length is greater than the word it is compared with...
 longestWord = strSplit[i].length; // ...then longestWord takes this new value
  }
 }
 /* Here strSplit.length = 9
  For each iteration: i = ? i < strSplit.length? i++ if(strSplit[i].length > longestWord)? longestWord = strSplit[i].length
  1st iteration:  0    yes    1 if("The".length > 0)? => if(3 > 0)?  longestWord = 3
  2nd iteration:  1    yes    2 if("quick".length > 3)? => if(5 > 3)? longestWord = 5 
  3rd iteration:  2    yes    3 if("brown".length > 5)? => if(5 > 5)? longestWord = 5 
  4th iteration:  3    yes    4 if("fox".length > 5)? => if(3 > 5)?  longestWord = 5 
  5th iteration:  4    yes    5 if("jumped".length > 5)? => if(6 > 5)? longestWord = 6 
  6th iteration:  5    yes    6 if("over".length > 6)? => if(4 > 6)? longestWord = 6 
  7th iteration:  6    yes    7 if("the".length > 6)? => if(3 > 6)?  longestWord = 6
  8th iteration:  7    yes    8 if("lazy".length > 6)? => if(4 > 6)? longestWord = 6 
  9th iteration:  8    yes    9 if("dog".length > 6)? => if(3 > 6)?  longestWord = 6 
  10th iteration:  9    no    
  End of the FOR Loop*/

 //Step 4. Return the longest word
 return longestWord; // 6
}

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

No comment:


function findLongestWord(str) {
 var strSplit = str.split(' ');
 var longestWord = 0;
 for(var i = 0; i < strSplit.length; i++){
 if(strSplit[i].length > longestWord){
 longestWord = strSplit[i].length;
  }
 }
 return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

2. Use the sort () method to find the longest word

For this solution, we will use the Array. prototype. sort () method to sort the array according to some sort criteria, and then return the length of the first element of the array.

The sort () method sorts the alternate elements of the array and returns the array.

As far as we are concerned, if we just sort arrays,


var sortArray = [ " The " ,  " quick " ,  " brown " ,  " fox " ,  " jumped " ,  " over " ,  " the " ,  " lazy " ,  " dog " ].sort();

We will get the following output:


var sortArray = [ " The " ,  " brown " ,  " dog " ,  " fox " ,  " jumped " ,  " lazy " ,  " over " ,  " quick " ,  " the " ];

In Unicode, numbers precede uppercase letters and lowercase letters.

We need to sort the elements according to some sort standard


[].sort(function(firstElement, secondElement) {  return secondElement.length  -  firstElement.length; })

Compare the length of the second element with the length of the first element in the array.


function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
 
 // Step 2. Sort the elements in the array
 var longestWord = strSplit.sort(function(a, b) { 
 return b.length - a.length;
 });
 /* Sorting process
 a   b   b.length  a.length  var longestWord
 "The"  "quick"   5   3   ["quick", "The"]
 "quick" "brown"   5   5   ["quick", "brown", "The"] 
 "brown" "fox"    3   5   ["quick", "brown", "The", "fox"]
 "fox"  "jumped"   6   3   ["jumped", quick", "brown", "The", "fox"]
 "jumped" "over"    4   6   ["jumped", quick", "brown", "over", "The", "fox"]
 "over"  "the"    3   4   ["jumped", quick", "brown", "over", "The", "fox", "the"]
 "the"  "lazy"    4   3   ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"]
 "lazy"  "dog"    3   4   ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]
 */
 
 // Step 3. Return the length of the first element of the array
 return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy", "The", "fox", "the", "dog"];
        // longestWord[0]="jumped" => jumped".length => 6
}

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

No comment:


var strSplit =  " The quick brown fox jumped over the lazy dog " .split( '   ' );
0

3. Use the reduce () method to find the longest word

For this solution, we will use Array. prototype. reduce ().

The method of reduce () is applied to 1 reservoir function and every 1 value of the array (from left to right) to reduce it to 1 value.

reduce () performs a callback function once for each element present in the array.

You can provide an initial value as the second parameter to be reduced, where we will add an empty string "".


var strSplit =  " The quick brown fox jumped over the lazy dog " .split( '   ' );
1

var strSplit =  " The quick brown fox jumped over the lazy dog " .split( '   ' );
2

No comment:


function findLongestWord(str) {
 var longestWord = str.split(' ').reduce(function(longest, currentWord) {
 return currentWord.length > longest.length ? currentWord : longest;
 }, "");
 return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

Related articles: