Find the Longest Word in a String Problem

Find the Longest Word in a String Problem
0

#1

So I’m currently going through the algorithm section and encountering a lot of trouble.
I’m sure some of it is because I haven’t been writing in JavaScript for very long but I wanted to get some feedback from you guys and see if I am on the right road.

The code isn’t finished but I’m honestly scratching my head wondering what I have to do to make it to the solution.

Thoughts?

function findLongestWord(str) {

    // This will keep track of the longest word globally 
    
    var count = 0;

    // This code splits up the code into an array 

    var stringArray = str.split(' ');

    // This code checks the length of each item in the array 

    for (var i = 0; i < stringArray.length; i++) {
        if(stringArray[i].length > count) {
            stringArray[i].length = count;
        }
    }
    
    stringArray.forEach(function() {
        
    })
    return longestWord;
}

#2

The problem is that you never update the value of your “count” variable.

Also, there is something that you are doing, I don’t understand why, but I think that it’s not your idea:

The sentence stringArray[i].length = count;, what is doing is to replace the lenght value of each array position with the current count value. That it’s value is always zero.

My idea of solution:

Try to save a new count value each time you find a longer String than the previous one.
When the for bucle it’s done, your count variable should value the longest length of all Strings.