freeCodeCamp Challenge Guide: Find the Longest Word in a String

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 the length of that word.

Relevant Links


Hints

Hint 1

You will need to loop through the words in the string.

Hint 2

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

Hint 3

Do you remember how to get the length of strings?


Solutions

Solution 1 (Click to Show/Hide)
function findLongestWordLength(str) {
let longestLength = 0;
let currentLength = 0;

for (let i = 0; i < str.length; i++) {
  if (str[i] === " ") {
    if (currentLength > longestLength) {
      longestLength = currentLength;
    }
    currentLength = 0;
  } else {
    currentLength++;
  }
}
if (currentLength > longestLength) {
  longestLength = currentLength;
}

return longestLength;
}
Solution 2 (Click to Show/Hide)
function findLongestWordLength(str) {
  let words = str.split(' ');
  let maxLength = 0;

  for (let 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 3 (Click to Show/Hide)

Using .reduce()

function findLongestWordLength(s) {
  return s
    .split(' ')
    .reduce((longest, word) => Math.max(longest, word.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 longest, so that Math.max will know where to start.

Relevant Links

Solution 4 (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 5 (Click to Show/Hide)
function findLongestWordLength(str) {
  // split the string into individual words
  const words = str.split(" ");

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

  // if words has multiple elements, remove the first element
  // and recursively call the function
  return Math.max(
    words[0].length,
    findLongestWordLength(words.slice(1).join(" "))
  );
}

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

Code Explanation

The first line splits the string into individual words. Then we check if words only has 1 element left. If so, then that is the longest element and we return it. Otherwise, we remove the first element and recursively call the function findLongestWord, returning the maximum between the length of the first result and the recursive call .

Relevant Links

145 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.

2 Likes

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”);`

13 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”);

9 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");
24 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:

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

6 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?

4 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:

12 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

}`

2 Likes

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

1 Like

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