HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Function to find the shortest word in an array, where not every element is a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theshortestarraywherefunctioneverywordelementfindnot

Problem

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...

Solution

It seems odd to me that you loop through the array twice, once with every and once with filter. Why not just filter it and check if the filtered array has any elements? Also is there a reason why you used two different methods to check if the elements were strings? One more thing, I would have written the filter method as:

arr = arr.filter(function(e) { 
  return typeof e == 'string';
});


If you really want to do this using a single loop you could do something like:



` function findShortestWordAmongMixedElements(arr) {
return arr.reduce( function(shortest, e) {
return (typeof e == 'string') && (shortest=='' || e.length

Code Snippets

arr = arr.filter(function(e) { 
  return typeof e == 'string';
});

Context

StackExchange Code Review Q#163085, answer score: 6

Revisions (0)

No revisions yet.