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

Viewed 126

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!

3 Answers

Reduce the array to a pair of short and long values, and return the delta:

const findDelta = str => {
  const [long, short] = str.split(/\s+/)
    .reduce(([long, short], { length }) => [
      Math.max(long, length), // take the longest length
      Math.min(short, length) // take the shortest length
    ], [-Infinity, Infinity]) // init long with -Infinity and short with Infinity
    
  return long - short
}

console.log(findDelta("bitcoin take over the world maybe who knows perhaps"))
console.log(findDelta("turns out random test cases are easier than writing out basic ones"))

Solution

  • Map the array to the length of the words.
  • Then sort the array it will look like [2, 3, 4, 5, 6, 7, 7]
  • Then build the difference between the longest and the shortest word.

Thats your result

function findShort(s){

 s = s.split(" ");
 let leng = s.map((x) => {return x.length})
 leng.sort();
 return leng[leng.length-1] - leng[0];
}



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"));

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"));

Related