Added solution using map() (#34701)
* Added solution using map() * Update guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md Co-Authored-By: vzla0094 <43974195+vzla0094@users.noreply.github.com> * Update guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md Co-Authored-By: vzla0094 <43974195+vzla0094@users.noreply.github.com>pull/34810/head
parent
c7f8f8f75a
commit
933ef11154
|
@ -87,6 +87,32 @@ In case you're wondering about that `0` after the callback function, it is used
|
|||
* <a href='http://forum.freecodecamp.com/t/using-array-prototype-reduce-to-reduce-conceptual-boilerplate-for-problems-on-arrays/14687' target='_blank' rel='nofollow'>JS Reduce Made Easy</a>
|
||||
* <a href='http://forum.freecodecamp.com/t/javascript-math-max/14682.md' target='_blank' rel='nofollow'>JS Math Max</a>
|
||||
|
||||
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution 2:
|
||||
|
||||
**Using `.map()`**
|
||||
```javascript
|
||||
function findLongestWordLength(str) {
|
||||
return Math.max(...str.split(" ").map(word => word.length));
|
||||
}
|
||||
```
|
||||
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/6' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
### Code Explanation:
|
||||
|
||||
We provide `Math.max` with the length of each word as argument, and it will simply return the highest of all.
|
||||
|
||||
Let's analyze everything inside the `Math.max` parenthesees to understand how we do that.
|
||||
|
||||
`str.split(" ")` splits the string into an array, taking spaces as separators. It returns this array: \["The","quick,"brown","fox","jumped","over","the","lazy","dog"\].
|
||||
|
||||
Then, we will make another array, made from the lengths of each element of the `str.split(" ")` array with `map()`.
|
||||
|
||||
`str.split(" ").map(word => word.length)` returns \[3, 5, 5, 3, 6, 4, 3, 4, 3\]
|
||||
|
||||
Finally, we pass the array as argument for the Math.max function with the spread operator `...`
|
||||
|
||||
For more information on `map` <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map' target='_blank' rel='nofollow'>click here.</a>
|
||||
|
||||
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
|
||||
|
||||
**Using recursiveness**
|
||||
|
|
Loading…
Reference in New Issue