Finding length of shortest word in array?

Finding length of shortest word in array?
0

#1

Defining a function that when given 3 parameters ( word1, word2, word3) will give me the length of the shortest word. Here’s what I have so far:


function findMinLengthOfThreeWords( word1, word2, word3 ) {
  let words = [ word1, word2, word3];   // create an array of the words

  for ( i = 0; i < words.length; i++ ){   // Looping through the array to find index
    let length = words[i].length;    // Setting  variable 'length' as the length of an index in the array
    let min = Math.min(length);   // Setting variable 'min' to index in the array that's the shortest
    return min;   // min should return whatever length is the shortest?
  }
}

So far passing 2 of 3 test but why not the 3rd? Am I using Math.min() wrong? Is there a simpler method and I’m just complicating things?

Thanks in advance for all your help


#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Thanks @ ArielLeslie I’ll keep it in mind.

NVM :weary:

let words = [ word1, word2, word3];

 let min = Math.min(...words.map(({ length }) => length));

return min;

Guess I was using it wrong. Thing is I have absolutely no idea how this method even works. I was trying to solve it in a way I understand, but it’s just one of those things you just have to commit to memory I suppose.

So this is saying use .map() to create a function that loops through each index in an array, where ‘length’ is the length of each index. Then finding the Math.min() of that words.map() gives me the minLength?


#4

You could also just use <= to check if each index is less than the previous one and store those in a variable. Good use of spread operator.