Kōdo no musō-ka Kōdo no musō-ka - 1 year ago 64
Javascript Question

Returning the length of largest word in a sentence

I have written a function which receives a sentence and calculates the longest word in that sentence.

function findLongestWord(str) {

var charArray = str.split(" ");
var wordArray = [];

for(var i = 0; i < charArray.length; i++ ) {


return wordArray[0];

My function works with inputs such as:

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

But when i pass it:

findLongestWord("What if we try a super-long word such as otorhinolaryngology")

The function returns:


Rather than


Answer Source

According to the docs:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

Emphasis mine.

Hence your numbers are getting sorted as strings.

In your function you should instead do:

wordArray.sort(function(a, b) { return b - a; });

to sort them from highest to lowest.

You could also do it all in one pass:

function findLongestWord(str) {
  return str.split(/\s+/i).sort(function(a, b) { return b.length - a.length; })[0].length;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download