Search code examples
javascriptarraysfunctionnested-loops

Javascript: Writing a function that returns the longest word in a string. With NO jquery used


This is my first time posting here and I'm only doing this because I have researched all over the place. There are questions out there that are coded similarly but they weren't looking for the right thing that would help me.

var sentence = "The Shattuck is the best"

var longest = function(str) {
  var strArr = str.split(" ");
  for (var i = 0; i < strArr.length; i++) {
    for (var j = 0; j < strArr.length; j++) {
      if (strArr[i].length > strArr[j].length) {
        strArr.splice(j, 1);
      } else {
        j = 0
      }
    }
  }
  return strArr
};
longest(sentence);
//should return Shattuck but I get an infinite loop problem.


Solution

  • For browsers not supporting reduce try

    var sentence = "The Shattuck is the best"
    
    var lon=-1,len=0, longest=function(str) {
      if (str.length>0) { // make sure we have a string
        var strArr = str.split(" "); // split on space
        for (var i = 0; i < strArr.length; i++) { // loop
          if (strArr[i].length>len) { // if the new length is longer
            lon = i; // save the index 
            len=strArr[i].length; // overwrite the saved length
          }
        }
        return strArr[lon]; // return the longest
      }
    };
    var word = longest(sentence);
    alert(word)