简体   繁体   中英

find & return the longest word in javascript

Can someone please let me know what is going wrong here? Whenever I type in this as a test case (console.log(longestWord("what the hell is going on")) and I get 'what' back as the longest word...it works on pretty much every other case I tested ...its driving me crazy please help. thank you!!!

function longestWord(string) {
var words = string.split(' ');

for (var i = 0; i < words.length; i++) {
    var currentWord = words[i];

    var longestWord = words[0];

    if (longestWord.length < currentWord.length) {
         longestWord = currentWord;
    }
}
return longestWord;
}

You were resetting your longest word with every iteration of the loop. Set initial (first) longest word before the loop runs and then it will work properly.

 function longestWord(string) { var words = string.split(' '); // Set the intial longest word out here var longestWord = words[0]; // Need to loop through from index 1 for (var i = 1; i < words.length; i++) { var currentWord = words[i]; // Setting the longest word to the initial word here means that it will set the longest word to be "what" everytime your loop runs. if (longestWord.length < currentWord.length) { longestWord = currentWord; } } return longestWord; } console.log(longestWord("What the hell is going on")); 

Jordan has given you the correct answer. We can also use sort function and return the first element as follows:

 function longestWord(string) { var words = string.split(' '); return words.sort(function (a, b) { return b.length - a.length; })[0]; } console.log(longestWord("what the hell is going on")) 

I post the ES6 one-liner, just in case...

 let longestWord = str => str.split(' ').sort((a, b) => b.length - a.length)[0]; console.log(longestWord("what the hell is going on")); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM