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 18:01] – odefta | java-script:reduce:find-longest-word-from-a-string [2025/01/02 18:22] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| 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.1691431287.txt.gz · Last modified: (external edit)
