diff --git a/guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md b/guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md index 6bcde28b16..219a6b9cd5 100644 --- a/guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md +++ b/guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md @@ -87,6 +87,32 @@ In case you're wondering about that `0` after the callback function, it is used * JS Reduce Made Easy * JS Math Max +## ![: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:") Run Code + +### 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` click here. + ## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution: **Using recursiveness**