Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 3, 2022 12:07 am GMT

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;    });}

Original Link: https://dev.to/stuxnat/longest-word-algorithm-2j14

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To