DEV Community

stuxnat
stuxnat

Posted on

1 1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay