java-script:reduce:find-longest-word-from-a-string
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext 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 odefta | java-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 ====== | ||
+ | |||
+ | < | ||
+ | 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 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, | ||
+ | return word.length > maxWord.length ? word : maxWord; | ||
+ | }, '' | ||
+ | </ | ||
+ | </ | ||
<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