I\'m trying to find the longest word in a string, but it continually returns the length of the first word. Any ideas?
Here\'s my code:
function findL
here is how I did it.
function findLongestWord(str) {
var strArray =[];
var numArray=[];
var sortedNumArray=[];
strArray = str.split(" ");
numArray = strArray.map(function(val){return val.length;});
sortedNumArray=numArray.sort(function(a,b){return a-b;});
return sortedNumArray.pop();
}
Your return statement should be outside the for loop. It only executes the first loop then bails out.
Here is how I did it (I enclose a commented long version and a uncommented short version):
/***************
* LONG VERSION *
***************/
function findLongestWord(str) {
// Create an array out of the string
var arr = str.split(' ');
// Sort the array from shortest to largest string
arr = arr.sort(function(a, b) {
return a.length-b.length;
});
// The longest string is now at the end of the array
// Get the length of the longest string in the Array
var longestString = arr.pop().length;
// return the lenght of the longest string
return longestString;
}
/*****************
* SHORT VERSION *
****************/
function findLongestWord(str) {
return str
.split(' ')
.sort(function(a, b) { return a.length-b.length; })
.pop().length;
}
This is how I attempted to solve it:
function LongestWord(sen) {
var wordArray = sen.match(/\w+/gi);
var longest = 0;
var word = undefined;
for(var i = 0; i < wordArray.length; i++){
if(wordArray[i].length > longest){
word = wordArray[i];
longest = word.length;
}
}
return word;
}
Try using the following code sample:
function findLongestWord(str){
var arr=[];
arr=str.split(' ');
arr=arr.sort(function(a,b){
return b.length-a.length;
});
var st=arr[0];
return st.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Your return statement is misplaced, put it after the loop :
function findLongestWord(str) {
var words = str.split(' ');
var longest = 0;
for (var i=0;i<words.length;i++) {
if (words[i].length > longest) {
longest = words[i].length;
}
}
return longest;
}