Find the Longest word in a string

Find the Longest word in a string
0

#1

Hello, THIS WORKS.
But maybe you did it on another way, so share yours here, or give me your advices.
Thanks guys!!!

function findLongestWord(str) {
array = str.split(" ");
array2=0;
for(i=0;i < array.length;i++){
if(array[i].length >array2){
array2=array[i].length;}
}
return array2;
}

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


#2

I would probably used the same method, so my overall approach is the same. You can improve your code with better variable conventions though.

Variables should usually be declared with var so they are not treated as global variables. They should also have clear, descriptive names. With that in mind, here’s how I’d write your code:

function findLongestWord(str) {  
  var array = str.split(" ");  
  var lengthOfLongest = 0;  
  for(var i = 0; i < array.length; i++) {
    if(array[i].length > lengthOfLongest) {      
     lengthOfLongest = array[i].length;
    }
  } return lengthOfLongest;
}

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

#3

As an alternative, you can do a custom sort function, but it may be slower (haven’t tested the performance on it)

function findLongestWord(str) {
  array = str.split(" ");
  array.sort(function(a,b){
     return a.length - b.length;
  });
  return array[array.length - 1].length
}
findLongestWord("The quick brown fox jumped over the lazy dog");

#4

Thanks JacksonBates to notice that. I’m a new coder. So, thanks for the advices :+1:


#6

Or even this ugly to read ES6 stuff :

function findLongestWord(str) {

return str.split(" ").sort((a, b) => b.length - a.length)[0].length;

}

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

#7

More ugly ES6 code:

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

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

#8

I’m a newbie also. Here’s what I did…

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


#9

beauty is in the eye of the beholder. this is the most beautiful, elegant solution in my eyes.:slightly_smiling_face:


#10

This is how i did it:

function findLongestWord(str) {
str=str.split(" ");
for(i=0;i<str.length;i++){
str[i]=str[i].length;
}

str=str.sort(function(a,b){
return b-a;
});

return str[0];
}

findLongestWord(“May the force be with you”);


#11

Seeing a lot of ways I can make my code more concise by seeing everyone solutions.
Here is mine:

function findLongestWord(str) {

var words = str.split(’ ');

var nums = words.map(function(word){
return word.length;
});

nums.sort(function(a,b){
return a - b;
});

var result = nums.pop();

return result;
}


#12

This is my favorite because it’s the closest to plain language.

“Find the longest (Math.max) word (map words to length).”


#13

First I created for loop with length comparison. Then I wanted to use map and max methods and here is my code.

function findLongestWord(str) {
return Math.max.apply(null, str.split(" ").map(function(a) {return a.length;}));
}

-Zumi-


#14

Hey Jackson, when u will have 5 minutes could you explain me those bold line below : ( im get confused)

function findLongestWord(str) {
var array = str.split(" ");
var lengthOfLongest = 0;
for(var i = 0; i < array.length; i++) {
if(array[i].length > lengthOfLongest) { => here lengthOfLongest is still = 0 ?
lengthOfLongest = array[i].length;
}
} return lengthOfLongest;
}

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


#15

Sure thing:

function findLongestWord(str) {
  var array = str.split(" ");
  var lengthOfLongest = 0;
  for(var i = 0; i < array.length; i++) {
    if(array[i].length > lengthOfLongest) { 
      lengthOfLongest = array[i].length;
    }
  } 
  return lengthOfLongest;
}

Lines 4-7 are where the magic happen.

Basically, it loops through the array ['the', 'quick', 'brown'...] and compares the length of each item in the array to the variable lengthOfLongest.

The first time it runs, lengthOfLongest = 0. The length of array[0] is 3. Since 3 is greater than 0, the action in the if block is run, i.e. lengthOfLongest = array[0].length

The second time it runs, lengthOfLongest is now 3. The length of array[1] is 5. Since 5 is greater than 3, 5 becomes the new length…and so on.

Does that make sense?


#16

Yes that makes definitely more sense right now. :slight_smile: thanks you for your response !


#17

I think i am still confused about the loop stuff. And I really dont know how to proceed. Hopefully its my last question for you :slight_smile: Im not looking for an answer, I just need to understand how should I do and I think you can help me !

For example in the next challenge called “Title Case a Sentence” I made this :

First of all, my strategy is :

  1. From String Sentence => Array of words of that sentence : [“i’m”, “a”, “little”, “tea”, “pot”]
    NO PROBLEM FOR THIS its “Line 2” in the code below.

  2. From [“i’m”, “a”, “little”, “tea”, “pot”] => [ [“i”," ’ ",“m”], [“a”], [“l”,“i”,“t”,“t”,“l”,“e”], [“t”,“e”,“a”], [“p”,“o”,“t”] ]
    HERE THE PROBLEM START, to MAKE THIS I WANT TO MAKE A LOOP, AND ITS RETURNING ME ONLY THE FIRST ARRAY

  3. From [ [“i”," ’ ",“m”], [“a”], [“l”,“i”,“t”,“t”,“l”,“e”], [“t”,“e”,“a”], [“p”,“o”,“t”] ] => replace first index of the array to Uppercase.
    FIRST I NEED TO FIGURE OUT THE LOOP :smiley:


function titleCase(str) {                    //input: ("I'm a little tea pot");_
  arrayWord = str.toLowerCase().split(" ");  //output: ["i'm", "a", "little", "tea", "pot"]_
 
  for (var i = 0; i < arrayWord.length; i++){  
    return arrayWord[i].split("");          //output : problem only returning the first [0]
    
  }
 
}

titleCase("I'm a little tea pot");

#18

Yeah, your problem here is that return kicks you out of whatever loop or function you are in to return the value and STOP.

So, save return for the one time you want to return your actual answer. (You will often see return used many times, but it is usually because a function contains other functions, or higher-order functions like map, reduce or filter).

If you want an array of arrays, you can loop through them as you normally would, but you might want to nest a loop within a loop.

Here is a rough example (beware, they use up more computer resources AND more mental resources!):

var array = [[1,2,3], [4,5,6], [7,8,9]]          // Array of arrays
for (var i = 0; i < array.length; i++) {         // Outer loop
  for (var j = 0; j < array[i].length; j++)  {   // Inner loop
    console.log(array[i][j]);                    // what do you expect 
  }                                              // this to log?
}

This can take a bit of concentration to get the hang of, so read it a few times to figure out what it is doing.

Notice that the outer loop uses i as the counter / array index. This tracks the three items in the first level of the array.

The inner loop uses j as the counter / array index. This tracks the three items in each of the second level arrays! Also, notice that the inner loop compares j to the length of array[i], not just array like the previous one did…

Now, you may find that there is a better solution than using nested loops altogether…but hopefully this is enough of a pointer to help you understand your current approach.

To solve your return problem, try assigning values to variables or constructing new arrays. Only return the solution.

ps: here’s a pen that will show you what the nested loops I wrote do (but try and figure it out first!): http://codepen.io/Malgalin/pen/JRVZjE?editors=0012

Edit

Oh, and in future, please start a new thread if you have a question about a different challenge. You are likely to get more eyes on it :slight_smile:


#19

looks like I really took the long way round on this one but still delighted that it worked :slight_smile :slight_smile:

function findLongestWord(str) {
  var array = str.split(" ");
  var numArray = [];
  var i = 0;

while (i<array.length){
  numArray.push(array[i].length);
  i++;
}
  
   var sort = numArray.sort(function(a,b){
     return b-a;
   });
  
  return sort[0];
  
  
}

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

#20

I thought I was doing well on these challenges until I came up with this solution. So many variables and so many lines of code…

function findLongestWord(str) {
  var strArr = [];
  var numArr = [];
  var largest;
  strArr = str.split(" ");
  for (i=0;i<strArr.length;i++){
    var num = strArr[i].length;
    numArr.push(num);
    largest = Math.max.apply(Math, numArr);
  }
 return largest;
}

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

#22

I still feel so lost… but when I look at all of you guys solutions, and the different variations, it gives me hope! so I’m going to keep at it and do my best to come up with my own :slight_smile: thank you all for sharing!