DEV Community

stuxnat
stuxnat

Posted on

Longest Word Algorithm

In this post I will explain how to solve the longest word algorithm problem. This challenge asks to: return the longest word in a sentence as a string. If there are multiple words of the same length, return array.

Step 1.
Remove punctuation (like commas and periods). We will use .match on this to return a filtered array.

function longestWord(sentence) {
const words = sentence.match(/[a-z0-9]+/g) //global so it doesn't stop at first
}

Step 2. Sort by Length

We will use .sort and compare the words based on length in each iteration. They will be returned in sorted order.

function longestWord(sentence) {
const words = sentence.match(/[a-z0-9]+/g)
const sorted = words.sort(function(one, two){
return two.length - one.length
});
const longestArray = sorted.filter(function(word){
return word.length === sorted[0].length;
});
}

Step 3. Handle multiple words by putting them into array.

function longestWord(sentence) {
const words = sentence.match(/[a-z0-9]+/g)
const sorted = words.sort(function(one, two){
return two.length - one.length
});
const longestArray = sorted.filter(function(word){
return word.length === sorted[0].length;
});
}

Step 4. Check array length, and return based on length.

function longestWord(sentence) {
    const words = sentence.match(/[a-z0-9]+/g)

    const sorted = words.sort(function(one, two){
        return two.length - one.length
    });

  const longestArray = sorted.filter(function(word){
        return word.length === sorted[0].length;
    });
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)