function longestWord(string) {
var str = string.split(\" \");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
One advantage to taking a functional approach to such problems is that you don't even have to keep count
See MDN Array.reduce for more info. (note: reduce
needs shim for IE8)
function longer(champ, contender) {
return (contender.length > champ.length) ? contender : champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord("The quick brown fox jumped over the lazy dogs"));
You need to use:
for (var i=0;i<=str.length - 1; i++)
That way it will scan the entire phrase
Is there a specific reason
for (var i = 0; i < str.length - 1; i++)
isn't
for (var i = 0; i < str.length - 1; i++)
That seems like it could be the cause.
This seems to be the easiest way to do this.
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
Here is one other way to solve it.
function findLongestWord(str) {
var result = [];
var one = str.split(" ");
for (var i = 0; i < one.length; i++) {
result[i] = one[i].length;
result.reverse().sort(function(a,b) {
return b-a;
});
}
return result[0];
}
Here this is your solution with a forEach, this will help you avoid the error in the future
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
console.log(longestWord("pride and prejudice"));
Your original problem was just the str.length - 1
should have just been str.length
, originally you wouldn't have gotten to the last element of the array