Reputation: 1101
Desired outcome is a the length of the longest word in a given string (numerical).
Ex: findLongestWord('I like tacos'); => 5
I get the 'cannot read length of undefined' error message when I start the loop from the end, and I only get the first new value of 'longest' when I start the loop forward. What am I missing?
function findLongestWord(string) {
var longest = 0;
var array = string.split(' ');
for (var i = array.length; i >= 0; i--) {
if (array[i].length > longest) {
longest = array[i].length;
}
}
return longest;
}
Upvotes: 2
Views: 887
Reputation: 17858
Your for
loop first runs on i
index which points to array.length
that you're trying to access with the value of undefined
.
Taken from MDN, Array length returns a 32-bit integer that is always numerically gerater than the highest index of the array.
In short, array.length
is zero-based index.
So modifying your code to this will do,
function findLongestWord(string) {
var longest = 0;
var array = string.split(' ');
for (var i = array.length - 1; i >= 0; i--) {
if (array[i].length > longest) {
longest = array[i].length;
}
}
return longest;
}
But, here's another way you can achieve this...
function findLongestWord(str){
var longestWord = '';
str.split(' ').forEach(function (v) {
longestWord = v.length > longestWord.length ? v : longestWord
});
return longestWord;
}
var word = findLongestWord('I like tacos');
console.log(longestWord, longestWord.length);
// tacos 5
Upvotes: 1
Reputation: 4584
Using .sort
will be easy .When you sorted array in DESC order ,get longest string by just index 0.
function findLongestWord(string) {
var array = string.split(' ');
longest = array.sort(function(a,b){
return a.length < b.length;
});
return longest[0].length;
}
Upvotes: 1
Reputation: 1101
Thanks everybody for the great suggestions! I now see there are cleaner/shorter ways to handle this toy problem but I went with adding the 'length -1' to my loop, as that's the closest to what I had come up on my own.
Thanks!
Upvotes: 0
Reputation: 896
array.length returns ,n, the number of elements in the array and when we fetch elements from the array using index it is from 0 to n-1. So you will have to use array.length -1 instead of array.length.
Upvotes: 1
Reputation: 25850
change your for to for (var i = array.length - 1; i >= 0; i--) {
if there 4
elements in array index start from 0
to 3
hence in that case array[4]
is undefined
Upvotes: 1