Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the length of largest word in a sentence [duplicate]

Tags:

javascript

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++ ) {
    wordArray.push(charArray[i].length);
    wordArray.sort();
    wordArray.reverse();

  }

  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:

4

Rather than

19
like image 953
Kōdo no musō-ka Avatar asked Nov 16 '16 13:11

Kōdo no musō-ka


People also ask

How do you find the largest word in a string?

One of the approach to find smallest and largest word is to split string into words then, compare length of each word with variables small and large. If length of a word is less than length of small then, store that word in small. If length of a word is greater than length of large then, store that word in large.

How do you find the largest word in a sentence in Python?

Iterate over the characters of the string. Check if the current character encountered is a space or end of the string is reached. If the current character is found to be so, update the maximum length of a word obtained. Finally, print the longest word obtained using substr() method.

How do you find the largest word in a sentence in C++?

Solution Approach To find the smallest and largest word, we will find the length of each word by using two indexes, one for the start of the word and one for the ending which is marked using the ' ' (space character) or '\0' character. Then using the start and end index, we will find the maxLength and minlength.

How do you return the longest word in an array?

The For loop method Split the word into an array immediately using split(). After doing this, initialize the longest word to an empty string. Then use the for loop to map over the items in the array. The longest word returns as the word with the longest index.


2 Answers

Your sort function sorts the array lexically, so you end up with

[1,10,19,2,2,2,3,4,4,4]

reversing that, you get

[4,4,4,3,2,2,2,19,10,1]

where 4 is the first number

You don't need the sorting at all, just use Math.max instead

function findLongestWord(str) {
    return Math.max.apply( null, str.split(" ").map( (x) => x.length) );
}
like image 125
adeneo Avatar answered Nov 11 '22 08:11

adeneo


TL;DR

Your numbers are getting sorted as strings.

To get them sorted as numbers, in descending order, in your function you should instead do:

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

EXPLANATION

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.

[...]

Syntax

arr.sort()

arr.sort(compareFunction)

Parameters

compareFunction Optional

Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

Emphasis mine, so you end up with something like this:

var str = "What if we try a super-long word such as otorhinolaryngology";
var charArray = str.split(" ");
// now charArray == ["What", "if", "we", "try", "a", "super-long", "word", "such", "as", "otorhinolaryngology"]
// when you take the length of each word and end up with
var wordArray = [4, 2, 2, 3, 1, 10, 4, 4, 2, 19];
// and if you use plain wordArray.sort() without specific sort function you get
wordArray = [1, 10, 19, 2, 2, 2, 3, 4, 4, 4];
// and once reversed it is
wordArray = [4, 4, 4, 3, 2, 2, 2, 19, 10, 1];
// this is why you end up with wordArray[0] == 4

You could also implement the whole function as a one-liner:

function findLongestWord(str) {
  return str.split(/\s+/).sort(function(a, b) { return b.length - a.length; })[0].length;
}

console.log("Longest word length = ", findLongestWord("The default sort order is according to string Unicode code points"));

console.log("Longest word length = ", findLongestWord("What if we try a super-long word such as otorhinolaryngology"));
like image 25
Matteo Tassinari Avatar answered Nov 11 '22 07:11

Matteo Tassinari