My solution to "Find the Longest Word in a String". Opinions?

My solution to "Find the Longest Word in a String". Opinions?
0.0 0

#1
function findLongestWord(str) {
  
	var arr = str.split(' ');
	arr.sort(function(a,b) {
		return a.length < b.length;
	});
  return arr[0].length;
}

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

#2

This actually finds the length of the longest word and not the word itself.
You should be returning return arr[0]
However you can even be more efficient by using the Array.protoype.reduce() method


#3

His solution is correct. According to the first sentence in the exercise description.

Return the length of the longest word in the provided sentence.


#4

Oh alright. His post didn’t make it very clear. Thanks


function findLongestWord(str) {
  return str.split(' ').reduce(function(a, b) {
    if (a.length > b.length) {
      return a;
    } else {
      return b;
    }
  }).length;
}

findLongestWord('The quick brown fox jumped over the lazy dog'); // 6


#5

How do I improve my “code writing” to make it as neat as what youv’e wrote here? Its very hard for me to understand it.


#6

codepen has option called tidy in javascript you may use it :slight_smile:


#7

As @lkareeml said, you can use codepen’s tidy javascript to make your code cleaner (assuming you have correct syntax)
You can also use Markdown syntax to format javascript code on the freecodecamp forum.
You can see some cool Markdown helpers here: Markdown CheatSheet