|
| 1 | +// Longest Length |
| 2 | +// Write a function that takes in a string (a sentence) and returns the length of the longest string (longest word in that sentence) |
| 3 | + |
| 4 | +const longestLength = str => { |
| 5 | + return str.split(' ').sort((word1, word2) => { |
| 6 | + return word2.length - word1.length |
| 7 | + })[0].length |
| 8 | +} |
| 9 | + |
| 10 | +console.log(longestLength('I am a coding guru')) |
| 11 | +console.log(longestLength('Here and there and everywhere')) |
| 12 | +console.log(longestLength('The longest string')) |
| 13 | + |
| 14 | +// |
| 15 | +// |
| 16 | +// or using a forEach loop |
| 17 | +const longestLengthLoop = str => { |
| 18 | + let maxLength = 0 |
| 19 | + |
| 20 | + str.split(' ').forEach(word => { |
| 21 | + maxLength = maxLength < word.length ? word.length : maxLength |
| 22 | + }) |
| 23 | + |
| 24 | + return maxLength |
| 25 | +} |
| 26 | + |
| 27 | +console.log(longestLengthLoop('I am a coding guru')) |
| 28 | +console.log(longestLengthLoop('Here and there and everywhere')) |
| 29 | +console.log(longestLengthLoop('The longest string')) |
0 commit comments