User Tools

Site Tools


java-script:reduce:find-longest-word-from-a-string

This is an old revision of the document!


Find longest word from a string

The string is trimmed to remove any leading or trailing whitespace and split into an array of words using the regex /\s+/, which matches one or more whitespace characters:
The function then uses the reduce method on the array of words to find the longest word. The reduce method takes a callback function that compares the length of the current word to the length of the longest word found so far (maxWord):
.reduce((maxWord, word) => {
    return word.length > maxWord.length ? word : maxWord;
}, '')

Here's how the reduce method works:

  • maxWord: The accumulator that keeps track of the longest word found so far. It is initialized with an empty string * word: The current word being processed in the array. * The ternary operator (condition) ? valueIfTrue : valueIfFalse is used to compare the length of the current word with the length of maxWord. If the current word is longer, it becomes the new value of maxWord; otherwise, maxWord remains unchanged. * The final value of maxWord, once all the words in the array have been processed, is the longest word, and that's what the reduce method returns. </note> <code javascript longest-word-string.js> function findLongestWord(string) { if (typeof string !== 'string' || string.trim().length === 0) { return ;

}

  return string.trim().split(/\s+/).reduce((maxWord, word) => {
      return word.length > maxWord.length ? word : maxWord;
  }, '');

}

let longestWord = findLongestWord(“ abc def ghiiii axiiii ”); console.log(longestWord); Output: “ghiiii” </code>

java-script/reduce/find-longest-word-from-a-string.1691431398.txt.gz · Last modified: 2023/08/07 21:03 by odefta