Basic Algorithm Help


#1

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!


#2
  1. Formatted 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;
}
  1. To spot what you’re doing wrong it would be nice to know the actual outcome and desired outcome (or any errors if occuring).

To speed up the whole process:

  1. You use sort function, but you don’t sort your array. Please see this sort example: https://www.w3schools.com/jsref/jsref_sort.asp
  2. You set your variable answer to b.length that is an integer.
  3. 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.

#3

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");

#4

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.