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 21:03] – odefta | java-script:reduce:find-longest-word-from-a-string [2023/08/07 21:04] (current) – odefta | ||
---|---|---|---|
Line 6: | Line 6: | ||
< | < | ||
- | The function | + | 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> | <code javascript> | ||
.reduce((maxWord, | .reduce((maxWord, | ||
Line 12: | Line 12: | ||
}, '' | }, '' | ||
</ | </ | ||
- | |||
- | Here's how the reduce method works: | ||
- | |||
- | * **maxWord**: | ||
- | * **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**, | ||
</ | </ | ||
java-script/reduce/find-longest-word-from-a-string.1691431398.txt.gz · Last modified: 2023/08/07 21:03 by odefta