Practice Problem I am working on:
Write a function called "findShortestWordAmongMixedElements".
Given an
array,findShortestWordAmongMixedElementsreturns 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
"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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With