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

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);

}

3 Likes

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;
}
1 Like

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
1 Like

MapReduce approach :slightly_smiling_face:

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

1 Like
var findLongestWord=s=>Math.max(...s.split(' ').map(x=>x.length))

65 characters :wink:

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

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");

1 Like