Beruflich Dokumente
Kultur Dokumente
The split() method splits a String object into an array of strings by separating the
string into sub strings.
var strSplit = The quick brown fox jumped over the lazy
dog.split( );
If you dont add the space in the parenthesis, you will have this output:
var strSplit =
[T, h, e, , q, u, i, c, k, , b,
r, o, w, n, , f, o, x, , j, u, m,
p, e, d, , o, v, e, r, , t, h, e,
, l, a, z, y, , d, o, g];
function findLongestWord(str) {
var strSplit = str.split(' ');
var longestWord = 0;
for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length > longestWord){
longestWord = strSplit[i].length;
}
}
return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy
dog");
Find the Longest Word With the sort() Method
For this solution, we will use the Array.prototype.sort() method to sort the array
by some ordering criterion and then return the length of the first element of this
array.
The sort() method sorts the elements of an array in place and returns the
array.
In Unicode, numbers come before upper case letters, which come before lower
case letters.
[].sort(function(firstElement, secondElement) {
return secondElement.length firstElement.length;
})
where the length of the second element is compared to the length of the first
element in the array.
function findLongestWord(str) {
// Step 1. Split the string into an array of strings
var strSplit = str.split(' ');
// var strSplit = "The quick brown fox jumped over the
lazy dog".split(' ');
/* Sorting process
a b b.length a.length var longestWord
"The" "quick" 5 3 ["quick",
"The"]
"quick" "brown" 5 5 ["quick",
"brown", "The"]
"brown" "fox" 3 5 ["quick",
"brown", "The", "fox"]
"fox" "jumped" 6 3 ["jumped",
quick", "brown", "The", "fox"]
"jumped" "over" 4 6 ["jumped",
quick", "brown", "over", "The", "fox"]
"over" "the" 3 4 ["jumped",
quick", "brown", "over", "The", "fox", "the"]
"the" "lazy" 4 3 ["jumped",
quick", "brown", "over", "lazy", "The", "fox", "the"]
"lazy" "dog" 3 4 ["jumped",
quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]
*/
return longestWord[0].length;
The reduce() method applies a function against an accumulator and each value
of the array (from left-to-right) to reduce it to a single value.
reduce() executes a callback function once for each element present in the
array.
You can provide an initial value as the second argument to reduce, here we will
add an empty string .
function findLongestWord(str) {
var longestWord = str.split(' ').reduce(function(longest,
currentWord) {
return currentWord.length > longest.length ?
currentWord : longest;
}, "");
return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy
dog");