I believe my syntax is off. I am trying to find the longest string in array made from using .split to make a string into an array. Here’s my code:
function findLongestWord(str) {
var array = str.split(" ");
var answer = "";
array.sort(function (a,b) {
if (a.length < b.length) {
answer = b.length;
}
}
);
return answer.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Constructive criticism welcomed. Would be grateful if someone can spot what i’m doing wrong here!
You set your variable answer to b.length that is an integer.
You then try to return answer.length, so basically you do b.length.length trying to return length of integer variable. This will cast your integer to string (12 → “12”) and return length of that string.
Appreciate the help. I did some further reading and decided I was doing it all wrong because I only had half of the sort method. I instead used a for loop and it seemed to work. But thanks to your explanation I see where I went wrong. Thanks for your help!
Here is what I used to complete that excercise:
function findLongestWord(str) {
var array = str.split(" ");
var longest = 0;
for (var i = 0; i < array.length; i++) {
if (array[i].length > longest) {
longest = array[i].length;
}
}
return longest;
}
findLongestWord("The quick brown fox jumped over the lazy dog");