-2

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.
  • I reopened because the underlying problems the OP is trying to solve is different, there the misuse of a for loop leaving out the last word, whereas here it's an 'infinite loop' (apparently). I may well be wrong in reopening, though, I hadn't realised I had a golden open-hammer for questions I myself didn't close. – David Thomas Apr 19 '15 at 06:55
  • Well thanks David, I got some good info from mplungjan – Spencer Shattuck Apr 19 '15 at 07:36

3 Answers3

3

Array method reduce is an interesting approach that I would adopt.

var sentence = "The Shattuck is the best"
var words = sentence.split(" ")

words.reduce(function(a, b) {return a.length > b.length ? a : b})
// returns "Shattuck"
Leo
  • 13,428
  • 5
  • 43
  • 61
1

You can always sort the array based on word length and ask the program for the first value.

var Words = ["The", "Shattuck", "is", "the", "best"],
    sort = Words.sort(function (a, b) {
    return a.length < b.length;
});

console.log(sort);
console.log(sort[0]);
John
  • 353
  • 1
  • 5
  • 16
0

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)
mplungjan
  • 169,008
  • 28
  • 173
  • 236