function longestWord(string) {
var str = string.split(\" \");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
TRY THIS
function longest(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
Using the sort() method,this sorts the elements of an array by some ordering criterion and then returns the length of the first element of this array and hence the longest word.
function longest(string){
var longestWord = string.split(' ').sort(function(a,b){
return b.length - a.length;
});
return longestWord[0];
}
Another method is by using sort:
function longestWord(string) {
let longest = 0;
let str = str.split(" ").sort((word1,word2)=>{
});
return str[0].length;
}
longestWord('I love Python ')
function findLongestWord(str) {
let stringArray = str.split(" ");
stringArray.sort(function(a, b){
return a.split('').length < b.split('').length;
})
return stringArray[0];
}
findLongestWord("The quick brown fox jumped over the lazy dog");
// My simple solution.
const findLongestWordLength = str => {
let array = str.split(" ");
let longest = 0;
array.map(e => {
if (e.length > longest) {
longest = e.length;
}
})
return longest;
}
You can simplify your code with a library like Lo-Dash:
function longestWord(string) {
var words = string.split(' ');
return _.max(words, function(word) { return word.length; });
}