If there are two or more words that are the same length, return the first word from the string with that length. I am a beginner. Could anyone highlight good and bad parts of the following program.Also, had it been last word from the string with that length, would it give different result in Chrome and Firefox because of it being unstable in Chrome ?
function LongestWord(sen) {
var arr2=[];
var arr =sen.split(" ");
var arr1=arr;
arr.sort(function (a,b){
if(a.length<b.length){
return -1;
}
else if(a.length===b.length){
return 0;
}
else return 1;
});
var len =arr[arr.length-1].length;
for(var i =0 ; i<arr1.length;i++)
{
if(arr1[i].length===len)
{
arr2.push(arr[i]);
break;
}
}
return(arr2.pop());
}
1 Answer 1
Before I give you my answer, a bit of critique regarding your code:
- Naming convention in JS use camelCase.
- What is
sen
? By itself, it doesn't tell me what it is. Name your variables meaningfully, one that tells you what it does the first time you read it. - Be consistent with whitespace. Usually, there should be spaces before and after operators (ie.
a = b
,foo = []
etc.) - Indention. Always have proper indention.
- By sorting, you already fail the criteria of "first longest word prevails" because of sort instability.
You can simply use reduce
. Carry around the longest word through the array, replacing it when you find something longer.
function findLongestWord(sentence) {
return sentence.split(' ').reduce(function(longestWord, word){
return word.length > longestWord.length ? word : longestWord;
});
}
var str = "The quick brown fox jumps over the lazy dog";
document.write(findLongestWord(str));
-
1\$\begingroup\$ yo are using
longestWord
as variable and function name. Considere use different names. \$\endgroup\$vmariano– vmariano2015年09月25日 20:28:40 +00:00Commented Sep 25, 2015 at 20:28