User Tools

Site Tools


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

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:reduce:find-longest-word-from-a-string [2023/08/07 20:56] – ↷ Page moved from java-script:string:find-longest-word-from-a-string to java-script:reduce:find-longest-word-from-a-string odeftajava-script:reduce:find-longest-word-from-a-string [2023/08/07 21:04] (current) odefta
Line 1: Line 1:
 ====== Find longest word from a string ====== ====== Find longest word from a string ======
 +
 +<note>
 +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**:
 +</note>
 +
 +<note>
 +The function 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):
 +<code javascript>
 +.reduce((maxWord, word) => {
 +    return word.length > maxWord.length ? word : maxWord;
 +}, '')
 +</code>
 +</note>
  
 <code javascript longest-word-string.js> <code javascript longest-word-string.js>
java-script/reduce/find-longest-word-from-a-string.1691431016.txt.gz · Last modified: 2023/08/07 20:56 by odefta