简体   繁体   中英

Finding Longest & Shortest word in JavaScript

One of the question is to find longest word in a string & another one is to find the shortest word in a string.

I am trying to figure out the difference between solving them. I understand everything except why is "longestlength =0" for the longestlength instead of "longestlength = newString[0].length." I tried solving it with that and the output is undefined. Likewise, for the "shortestLength" if I initialize it with "0" instead of "newString[0].length" I get undefined but I don't understand the reason behind it.

//code for longest string

 function longestWord(string) { 
let newString =string.split(" ");
let longestWord;
let longestlength= 0;
for(let i=0; i<newString.length; i++){
if(newString[i].length > longestlength){
  longestlength = newString[i].length;
  longestWord= newString[i];
 }
  }
 return longestWord;
  }

 //code for shortest string
  function shortestWord(string) {
 var stringArray = string.split(" ");  
  var shortestWord;
  var shortestLength = stringArray[0].length; 
  for(var i = 0; i < stringArray.length; i++){
   if(stringArray[i].length < shortestLength){
  shortestLength = stringArray[i].length;   
  shortestWord = stringArray[i];            
  }
    }
return shortestWord;
  }

Your problem can be solved in one line using reduce .

Longest word:

string.split(' ').reduce((acc, cur) => acc.length >= cur.length ? acc : cur);

Shortest word:

string.split(' ').reduce((acc, cur) => acc.length <= cur.length ? acc : cur);

Here's why your code might not work : In shortestWord , you set the current shortest length to the length of the first word in the array, but you don't set the shortest word to the first word in the array, it is still undefined. If the first word in the array happens to be the shortest word, no word is shorter, therefore no word will ever be assigned to shortestWord and the function will return undefined .

Solution : Replace

var shortestWord;

with

var shortestWord = stringArray[0];

longestlength has always have to match longestWord . If you set the length, but not the word itself, and if the length is actually the longest one, longestWord gets returned although it is yet empty.

To avoid such mistakes, just keep the word itself, and check its length with .length :

  function longest(words) {
    let longest;
    for(const word of words.split(" "))
      if(!longest || word.length > longest.length) // swap this to get the "shortest"
        longest = word;
    return longest;
 }
function longest(str){
    return str.split(" ").reduce((a,b)=> b.length >= a.length ? b : a,'')
}

function shortest(str){
    return str.split(" ").reduce((a, b)=>a.length <= b.length ? a : b, '')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM