freeCodeCamp Challenge Guide: Find the Longest Word in a String

freeCodeCamp Challenge Guide: Find the Longest Word in a String
0

Find the Longest Word in a String


Problem Explanation

You have to go through each word and figure out which one is the longest and return not the word, but how many characters it has.

Relevant Links


Hints

Hint 1

You should split the string into an array of words.

Hint 2

You will need to figure out a way to keep track globally of the greatest current length.

Hint 3

Remember how to get the length of elements on the array? Array[index].length.


Solutions

Solution 1 (Click to Show/Hide)
function findLongestWordLength(str) {
  var words = str.split(' ');
  var maxLength = 0;

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }

  return maxLength;
}

Code Explanation

Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.

Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.

Relevant Links

Solution 2 (Click to Show/Hide)

Using .reduce()

function findLongestWordLength(s) {
  return s.split(' ')
    .reduce(function(x, y) {
      return Math.max(x, y.length)
    }, 0);
}

Code Explanation

For more information on reduce click here.

In case you’re wondering about that 0 after the callback function, it is used to give an initial value to the x, so that Math.max will know where to start.

Relevant Links

Solution 3 (Click to Show/Hide)

Using .map()

function findLongestWordLength(str) {
  return Math.max(...str.split(" ").map(word => word.length));
}

Code Explanation

We provide Math.max with the length of each word as argument, and it will simply return the highest of all.

Let’s analyze everything inside the Math.max parenthesees to understand how we do that.

str.split(" ") splits the string into an array, taking spaces as separators. It returns this array: [“The”,"quick,“brown”,“fox”,“jumped”,“over”,“the”,“lazy”,“dog”].

Then, we will make another array, made from the lengths of each element of the str.split(" ") array with map().

str.split(" ").map(word => word.length) returns [3, 5, 5, 3, 6, 4, 3, 4, 3]

Finally, we pass the array as argument for the Math.max function with the spread operator ...

For more information on map click here.

Solution 4 (Click to Show/Hide)

Using recursion

function findLongestWordLength(str) {
  //split the string into individual words
  //(important!!, you'll see why later)
  str = str.split(" ");

  //str only has 1 element left that is the longest element,
  //return the length of that element
  if (str.length == 1) {
    return str[0].length;
  }

  //if the first element's length is greater than the second element's (or equal)
  //remove the second element and recursively call the function)
  if (str[0].length >= str[1].length) {
    str.splice(1, 1);
    return findLongestWordLength(str.join(" "));
  }

  //if the second element's length is greater thant the first element's start
  //call the function past the first element
  if (str[0].length <= str[1].length) {
    // from the first element to the last element inclusive.
    return findLongestWordLength(str.slice(1, str.length).join(" "));
  }
}

Code Explanation

The first line splits the string into individual words. Then we check if str only has 1 element left then that is the longest element and we return it. If the first element’s length is greater than the second element’s (or equal), we remove the second element and recursively call the function findLongestWord. However, if the second element’s length is greater thant the first element’s start, then we call the function past the first element.

Relevant Links

11 Likes

The JS Math Max link in the intermediate function explanations returns-

{“errors”:[“The requested URL or resource could not be found.”],“error_type”:“not_found”}

It might just be to MDN anyway, but I didn’t know if it was a special FCC article.

First ,when i use split(), I found str1 is a list, so , I just think why not get a list which contain every word’s length.
So I get a list of number, next problem is found the max number of the list, just google js max, so i get the solution.
I have compare my solution with official, my solution is not perfect ,but it’s a another way.
I feel happy with that.

`function findLongestWord(str) {
var str1 = str.split(" ");
var list = [];
for (i=0;i<str1.length;i++) {
list.push(str1[i].length) ;
}
return Math.max.apply(null ,list);
}

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

5 Likes
function findLongestWord(str) {

return str.split(’ ').map(function(val){
return val.length;
}).sort(function(a, b){
return b - a;
})[0];

}

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

8 Likes

This is my solution:

function findLongestWord(str) {
  
  var arr = str.split(" ");//split sentence to an array
  var longestWord = arr[0];//assume longest word is the first word of an array
  for (var i=0; i< arr.length; i++){ //iterate through array of words
    
    if(arr[i].length > longestWord.length){
      //compare other words of an array if they are longer than the first one
      longestWord = arr[i];
    }
  }
  return longestWord.length;//return length of the longest word
  
}
//test
findLongestWord("What if we try a super-long word such as otorhinolaryngology");
7 Likes

Here is my take on a solution.

function findLongestWord(str) {
    return Math.max.apply(Math, str.split(' ').map(val = val => val.length));
}

Update ES6 Spread Operator:

function findLongestWord(str) {
    return Math.max(...str.split(' ').map((word) => word.length));
}

:slight_smile:

5 Likes

Hi! I wanted to contribute with my solution :slight_smile:

function findLongestWord(str) {

  // Split the string into an array
  var array = str.split(" "); 

  // Then sort the array by its elements length, from longest to shortest
  array.sort(function(a,b) {
    return b.length - a.length; 
  });
  
  // Since the first element of the array will be the longest, then return the length of the first element
  return array[0].length; 
}

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

Hi , i did it w/ sort function;

function findLongestWord(str) {
   var abc = str.split(" ");
   var newStr = [];
   for (var i = 0; i < abc.length; i++) {
   	
   	 newStr.push(abc[i].length);
   }
     var neweSTr= newStr.sort(function(x,y){return y -x;}); 	
   return neweSTr[0];
}

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

5 Likes

Very short code; how you managed to simply write var longestWord in a such way in if condition ; Appreciate Really!! your logic;

      function findLongestWord(str) {

       var arr = str.split(" ");//split sentence to an array
       var longestWord = arr[0];//assume longest word is the first word of an array
       for (var i=0; i< arr.length; i++){ //iterate through array of words

if(arr[i].length > longestWord.length){
  //compare other words of an array if they are longer than the first one
  console.log(longestWord = arr[i]);
 }
 }
return //console.log(longestWord.length);//return length of the longest word
 
}
  //test
 findLongestWord("What if we try a super-long word such as otorhinolaryngology");

`
examining your code, where I have written console log in gives two strings, while should give just a lonestWord; Why could you explain me plz
Thanks ahead

1 Like

What is the advantage of the Advanced/ Intermediate Code over the Basic?

3 Likes

Hi there! This is my solution.

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

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

:grin:

10 Likes

Here is my take:slight_smile:
:slight_smile:

function findLongestWord(str) {
// Split the string into an array
var array = str.split(" ");
var lengths = array.map(function(word){
return word.length
})
var q = Math.max.apply(null, lengths);

return q

}`

1 Like

I really like the solutions using .reduce but I was wondering whether it is noticeably faster than the Basic Code Solution.

function findLongestWord(str) {

var word = str.split(’ ');
var x = word[0].length;

for(i=0; i<word.length; i++){
if(word[i].length>x){
x = word[i].length;
}
}

return x;
}

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

My solution here i used the .toLowerCase() so when sorted, it would not put the capital string first but any comments on my solution would help thanks.

function findLongestWord(str) {
var strArry=[];

strArry=str.toLowerCase().split(’ ');
strArry.sort(function(a,b){
return b.length-a.length;
});

return strArry[0].length;
}

findLongestWord(“What if we try a super-long word such as otorhinolaryngology”);

2 Likes

I managed to reach the basic solution, and looking at the hints am trying to do the advanced solution, but am encountering a “Type Error: str.splice is not a function” error message that for the life of me I can’t figure out. Can anyone explain my mistake? Code is below, but I also had an question about the intermediate solution:

function findLongestWord(str) {

if (!str.isArray) {
str.split(" ");}

if (str.length == 1) {
return str[0];
}

if (str[0].length >= str[1].length) {
str.splice(1,1);
return findLongestWord(str);
}

if (str[0].length <= str[1].length) {
str.splice(0,1);
return findLongestWord(str);
}

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

Regarding the intermediate solution, can someone please explain the logic behind function(x, y) {
return Math.max(x, y.length)
}

Thanks

Hi @Alais29,

I did the exact same thing :slight_smile: .

Why doesn’t this work?

var array = [];
function findLongestWord(str) {
  var newArray = str.split(" ");
  
  for (i = 0; i < newArray.length; i++) {
    var newLength = newArray[i].length;
    array = array.concat(newLength);
    
  }
  return array.reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});
    
  
}

findLongestWord("May the force be with you");