Basic Algorithm Scripting – Find the Longest Word in a String

Basic Algorithm Scripting – Find the Longest Word in a String

Problem Statement ( Find The Longest Word in a String ) :

Return the length of the longest word in the provided sentence.

Your response should be a number.

Solution :

function findLongestWord(str) {
  var s = str.split(" ");
  var max = s.sort(function(a,b){
    return b.length - a.length;
  });
  return max[0].length;
}

Explanation :

The task is to find the longest word in the given sentence. The first thing that comes to anyone’s mind (or at least mine) is to just check the length of each word. So, how can we do it? The first thing that we need to do is to convert that sentence into an array of words. That is what wouldstr.split(" ") do. It would create an array of words by splitting the sentence using [space] as the delimiter.

Now what I did was to sort the array using each item’s length (descending order). We can achieve that by giving a compare function to javascript’s sort() function.

And then at last, as we have the longest word in the first position in our max[] element, we can just print the length of that element.

You can find more problems solved in FreeCodeCamp – Basic Algorithm Scripting – Solved.

www.000webhost.com