How can I find the longest words in the string and return those (excluding duplicates) along with maximum length?
function longestWord(sentence) {
// First we divide the sentence into words
var words = sentence.split(' ');
// We then get the length by getting the maximun value of the length of each word
var length = Math.max(...words.map(a=>a.length));
return {
length: length,
// Finally we filter our words array returning only those of with the same length we previously calculated
words: words.filter(i => i.length == length)
}
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));
You may do that with Array.prototype.reduce()
by a single pass through the array (without extra looping for calculating maximum length).
The idea is to reset resulting array with a single word, once its length exceeds those that were inserted before or append if current word happens to have same length, or simply pass by otherwise:
const src = 'The quick brown as bbbbbb fox jumped over the jumped lazy dog',
result = src.split(' ')
.reduce((res, word, idx) => {
if(!idx || word.length > res.length)
res = {length: word.length, words:new Set([word])}
else if(word.length == res.length)
res.words.add(word)
return res
}, {})
console.log({result: result.length, words: [...result.words]})
.as-console-wrapper {min-height:100%}
You could take a single loop approach and check the legth fot each word with the accumulators length of the first item.
function longestWords(words) {
return words
.split(/\s+/)
.reduce((accu, word) => {
if (!accu[0] || accu[0].length < word.length) return [word];
if (accu[0].length === word.length) accu.push(word);
return accu;
}, []);
}
console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));