# Find Longest Word in a String[Compact Solution-SPOILER ALERT!]

Find Longest Word in a String[Compact Solution-SPOILER ALERT!]
0

#1

I am posting my solution to the problem to get some feedback. I tried to solve it with as few lines as possible. Is there anyway I could make it even more compact or would that make the code too unreadable?

function findLongestWord(str) {

var wordArray = str.split(" ").sort(function(a,b){return(a.length-b.length);});
return(wordArray[wordArray.length -1].length);

}

#2

Pretty much the same, except that I’ve used shift() to return the first array

``````function findLongestWord(str) {
return str.split(' ').sort(function (a,b) {return b.length - a.length}).shift().length;
}
``````

#3

This is about as short as I can make it:

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

#4

Using `.reduce`

``````function findLongestWord(str) {
return str.split(' ').reduce( (l, c) => l.length > c.length ? l : c ).length;
}

findLongestWord('a aa aaaa aaa aaaaaaaa aaa'); // 8
``````

#5

Another version using reduce:

``````function findLongestWord(str) {
return str.split(' ').reduce( (long,w) => Math.max(long,w.length),0);
}
``````

#6

MapReduce approach

``````function findLongestWord(str) {
return str
.split(' ')
.map((val) => {
return val.length;
})
.reduce((a, b) => {
return (b > a) ? b : a;
});
}

``````

#7
``````var findLongestWord=s=>Math.max(...s.split(' ').map(x=>x.length))
``````

65 characters

(With apologies to @RandellDawson’s first solution above)

#8

this is solution

``````
function findLongestWord(str) {
var max,
newArr = [];
var arr = str.split(' ');
for(i = 0; i < arr.length; i++) {
newArr.push(arr[i].length);
}
return newArr.reduce(function(a,b) {
return Math.max(a,b);
});
}

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

``````

#9

A post was split to a new topic: Find longest word in a string - problem with my code