Hi coders..if anyone could assist me..I'v been stuck for a while now..keeps on resulting in an empty array


#1

var longestWord = function(string) {
//var wordLength = longestWord.length
var longWord = []
var sentence = string.split(',');
for (var i = 0; i < sentence.length; i++) {
if (sentence[i] < longWord) {
//wordLength = sentence.length
longWord.push(sentence[i]);
}
}

return longWord;

}
var longer = longestWord('I applied to an open collaboration at workshop 17');
console.log(longer);


#2

i would do it slightly different:

var longestWord = function(string) {
//var wordLength = longestWord.length
  var longWord = "";
  var sentence = string.split(' ');
  for (var i = 0; i < sentence.length; i++) {
    if (sentence[i].length > longWord.length) {
      //wordLength = sentence.length
      longWord = sentence[i];
    }
  }
  return longWord;

}
var longer = longestWord('I applied to an open collaboration at workshop 17');
console.log(longer);

i would start by splitting the word by spaces rather then comma's (since there are spaces between the words, and no comma's)

then i would make longWord and empty string, and check if the length of sentence[i] is greater then the length of longWord. If so, set longWord to this word

drawbacks of this method: not very efficient, if there is a second word which is equally long, only the first one would be find.


#3

so the .push method was not required at all?. that made it crystal clear..thanks for your generosity..


#4

well the push method would have put multiply items in the array, which wouldn't give you the longest word


#5

oh okay..so now I will be able to find the shortest word on my own thanks to you again..lol


#6

yea, you should be able to manage that.