In this exercise we are given the following snippet to find the longest word in the sentence.
findLongestWordLength(str) {
return maxLen
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
Below are our attempts
//Attempt 1 | |
function findLongestWordLength(str) { | |
let arr=str.split('') | |
let maxLen=0; | |
for(let i=0;i<arr.length;i++){ | |
if(arr[i].length>maxLen){ | |
maxLen=arr[i].length | |
} | |
} | |
return maxLen | |
} | |
//Attempt 2 | |
function findLongestWordLength(str) { | |
let arr=str.split(' ') | |
let maxLen=0; | |
for(let i=0;i<arr.length;i++){ | |
if(arr[i].length>maxLen){ | |
maxLen=arr[i].length | |
} | |
} | |
return maxLen | |
} |
What is the correct answer? Attempt 2 as always, the reason being..
The split function
Top comments (0)