function findLongestWordLength(str) {
//Creating the regex and adding the solution in the array
let word = [];
let regex = /[A-Za-z]+S/g;
let result = str.match(regex);
word.push(result);
//Iterating the array using forEach
let currentWord = 0;
word.forEach((element) => {
element.forEach((element2) => {
let longestWord = element2.length;
if (currentWord < longestWord) {
currentWord = longestWord;
}
});
});
//It returns the longest word (the length of that word)
return currentWord;
}
console.log(
findLongestWordLength("The quick brown fox jumped over the lazy dogs")
);
This is a good solution but can be this algorithm improved ?
Help me guys out to find a simplify solution
I need feedback about this code I made
Thanks
2
Answers
Just compact and make it more readable and simplify it to this?
Slightly shorter, return the longest word:
Or if you just want the length of the longest word (your subject says the longest word but your code says the longest word length):