Search code examples
javascriptarraysstringfor-loopstring-length

Return the difference between the lengths of the shortest and longest words (using for loop)


I'm wondering how to return the difference between the lengths of the shortest and longest words (using a for loop):

function findShort(s){

 s = s.split(" ");

   (for let i = 0; i < s.length; i++) {
   ******code goes here******
}

}

findShort("bitcoin take over the world maybe who knows perhaps");
findShort("turns out random test cases are easier than writing out basic ones"); 
});

Any ideas? If someone would also like to try using something like map or reduce that would also be appreciated.

Cheers!


Solution

  • No need for for loops. Just map the sentence into a list of word lengths, find the longest and shortest and subtract:

    function findShort(sentence) {
      const lengths = sentence.split(/\s+/).map(word => word.length);
      
      return Math.max(...lengths) - Math.min(...lengths);
    }
    
    console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
    console.log(findShort("turns out random test cases are easier than writing out basic ones"));