简体   繁体   中英

How to find length of shortest word in an array in Javascript?

I'm trying to find the shortest word in an array. I am using this code

function findShortestWord(str) {
  var strSplit = str.split(' ');
  var shortestWord = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > shortestWord){
    shortestWord = strSplit[i].length;
     }
  }
  return shortestWord;
}

which actually finds the longest word. I just need to change it up to find the smallest word. I'm having trouble figuring out what to set the shortestWord variable to and how i should implement that on the if statement

function findShortestWord(str) {
  var strSplit = str.split(' ');
  var shortestWord = strSplit[0].length;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length < shortestWord){
    shortestWord = strSplit[i].length;
     }
  }
  return shortestWord;
}

Just grab the first word in your list, and set that as the current "shortest length". Compare all other words to your shortest length, and update as you go. Currently this will only show you the first shortest word, and not all words of that length.

Your code is returning largest number because of you if condition. Use < instead of > and initialize your return variable correctly. Posting the solution with corrections below:

function findShortestWord(str) {
  var strSplit = str.split(' ');
  var shortestWord = strSplit[0].length;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length < shortestWord){
    shortestWord = strSplit[i].length;
     }
  }
  return shortestWord;
}

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