mardi 21 novembre 2017

Javascript - 128_findShortestWordAmongElements -- Given an array of different type elements, find the string with the shortest word

I'm doing exercises from Hackreactor and i am currently stuck on this one:

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

var output = findShortestWordAmongMixedElements([4, 'two', 2, 'three']);
console.log(output); // --> 'two'

*/

So far, this is what I have:

function findShortestWordAmongMixedElements(arr) {
  // your code here
  var array = [];
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] === 'string') {
      array.push(arr[i]);
      array.sort(function(a,b) {
        return a.length - b.length;
      });
      return array[0];
      } 
    } 
  } 

it returns the word i want, but i am not able to fulfill the failing conditions. What i've tried is, is that i put an if statement after return array[0] that if the type of element that returns is undefined, it returns an empty string. This does not work at all. I also put an if statement for if (arr.length > 0), returning an empty string if the array is empty using ||. This works, but the other one doesn't. Is there a way i can implement these failing conditions in my code?

Aucun commentaire:

Enregistrer un commentaire