I have been tasked with this question:
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
I wrote a code as follows:
function findShort(s){
//var word = s.split(' ')
var result = parseInt(word.map(a => a.length))
return result
return Math.min(result)
}
the output keeps bring the length of the first word instead of the shortest word.
What might be the problem?
4
Answers
parseInt(word.map(a => a.length))
this will convert the result ofmap()
into an integer, you don’t want that.Also, you can’t return twice from the same function call, so the second
return
will never be reached.Math.min()
excepts multiple values as arguments, not an array, use the spread syntax (...
) to pass the values as arguments instead of an arrayThat said, you could also use
reduce()
to compare 2 words, and only ‘keeping’ the length of the shorter one:Simply iterate but the thing here I believe is to what thing to initialize. Thinking about a little bit, You can discover You can need to initialize somewhere depending on how you are iterating the list. In my case, I decided to initialize with the first word.
Since apostrophes do not typically count toward the length of a word in most contexts, you should probably add an option to handle them.
I added a
prune
flag to the function to remove non-word characters when determining the length of a word.Split and reduce!