find longest word in the sentence

longest word in the sentence

Find the longest word in the sentence

I am using javascript for this question.

It can be done in a lot of ways. The straight forward way could be the fastest probably. You will loop over the array of the words – you can split it with space – ” “.

Then just compare the value of the word length with maximum value and overwrite when it is higher – you know what I mean..

I will show the single liner for this though

var longestWord = "Guess what the longest word in the dictionary is".split(" ").sort(function(a, b){
    return b.length - a.length;

Let’s go through what is going on..

The first part "Guess what the longest word in the dictionary is" is the given example sentence we are trying to find the longest word for.

Then we split the string into array of words using the split(" ") function. Now we have array to work with.

Then we sorted the array with sorter function passed to it. Sorter function in this one is anonymous function that we pass to it.

Finally we just took the first element of the sorted array which is sorted by the length of the word.

Also with the same concept, we have have it using reduce function;

"I still am having the wonderfulness of this thing ".split(" ").reduce((word1, word2) => word2.length > word1.length ? word2 : word1 );

That is it!

Check if Function Exists in Javascript

Java solution for checking anagram strings – tell if phrases are anagrams

Check if two strings are anagrams or not

Find K Complementary numbers from array Java implementation

Find longest palindrom from sequence of characters

how to get user input and process it in nodejs tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *