Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a mixed array contains string elements?

Practice Problem I am working on:

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.

This is currently what I have coded:

function findShortestWordAmongMixedElements(array) {
  if (array.length === 0)) {
    return '';
  }
  var result = array.filter(function (value) {
    return typeof value === 'string';
  });
  var shortest = result.reduce(function (a, b) {
    return a.length <= b.length ? a : b;
  });
  return shortest;
}

var newArr = [ 4, 'two','one', 2, 'three'];

findShortestWordAmongMixedElements(newArr);
//returns 'two'

Everything works but I can't figure out how to pass the "if given array contains no strings" test. I was thinking of adding some kind of !array.includes(string??) to the if statement but am not sure how to go about it.

Any hints? or even smarter way to write this function

like image 735
jalexyep Avatar asked Dec 04 '25 15:12

jalexyep


1 Answers

"Everything works but I can't figure out how to pass the "if given array contains no strings" test."

You are already using .filter() to get an array of just the strings. If that result array is empty then there were no strings. (I'm assuming you don't need me to show code for this, because you already have code that tests if an array is empty.)

like image 101
nnnnnn Avatar answered Dec 07 '25 05:12

nnnnnn