I wrote a solution for a codeCamp exercise:
Write a function called
findShortestWordAmongMixedElements
.Given an array,
findShortestWordAmongMixedElements
returns the shortest string within the given array.Notes:
- If there are ties, it should return the first element to appear in the given array.
- Expect the given array to have values other than strings.
- If the given array is empty, it should return an empty string.
- If the given array contains no strings, it should return an empty string.
Right now I essentially break this function into two parts. The filtering method—to just get the strings—and then reduce
to find the shortest one among them.
function findShortestWordAmongMixedElements(arr) {
var containsStrings = function(arr){
return arr.every(function(cv){
return Object.prototype.toString.call(cv) !== '[object String]';
});
}, shortestWord;
if ((!(arr.length)) || ((containsStrings(arr)))) return '';
arr = arr.filter(function(e, i, a){
if (typeof e == 'string') {
return e;
}
});
shortestWord = arr.reduce(function(prev, next) {
if (prev.length < next.length) {
return prev;
} else if (prev.length === next.length){
return prev;
} else {
return next;
}
});
return shortestWord;
}
My take is this is certainly readable which I like and I LOVE the helper function I made for the initial check which uses the every
method.
Since (at first) I spent a lot of time trying to do all the operations within the body of the callback for the filter—I feel this take is like I used flat head screw driver for every screw instead of a phillips...