arrays - Javascript : ask an explanation -
here's full code:
function longestword(sen) { // use regex match function searches string // pattern , returns array of strings finds // in our case pattern define below returns words // characters through z , 0 through 9, stripping away punctuation // e.g. "hello$% ##all" becomes [hello, all] var arr = sen.match(/[a-z0-9]+/gi); // array sort function takes function parameter // used compare each element in array // next element in array var sorted = arr.sort(function(a, b) { return b.length - a.length; }); // array contains words in original // string in order longest shortest length // return first element return sorted[0]; }longestword("the $$$longest# word coderbyte");
but need explain part :
var sorted = arr.sort(function(a, b) { return b.length - a.length; });
i understand how function , sort works, kinda mixed , brain crashed. , can give me simple alternative solve problem >> longest word, in using if-else
, comparing ?
for sort()
function can refer documentation
for simpler alternative see following code
function longestword(sen) { let longest = ""; sen.match(/[a-z0-9]+/gi).foreach(function(word) { if (word.length > longest.length) longest = word; }) return longest; } console.log(longestword("the $$$longest# word coderbyte"));
Comments
Post a Comment