I am not satisfied with my implementation of '.reduce' here. The goal of this problem is to return the length (mind not the word itself!) of the shortest word in an array. As we need to have a value for the first call of the accumulator that is very big to allow .reduce to compare word's length to the accumulator I have used 'Infinity'... Is there a better/more elegant way of using .reduce here? Thanks
function getLengthOfShortestElement(arr) {
return arr.reduce(function(acc, element) {
if (element.length < acc) {
acc = element.length;
}
return acc;
},Infinity);
}
I think your solution is just fine. But if using
Infinity
like this bothers you, you could just set the initial accumulator to zero. Then your first element would be the new accumulator on the first pass.Example: