My failed attempt to pull out the shortest string from an array filled with different types of primitives. What am I doing wrong? Are there any other wa
var bands = ([30, 'Seconds', 'to', 'Mars', 1, 'Direction', true]);
function tinyString(collection) {
var tinyStr = '';
return collection.
filter(function (x) {
return typeof x === 'string'
}).
forEach(function (y) {
if (tinyStr > y){
return tinyStr = y
}
})
}
console.log(bands); // --> 'to'
You can sort on length and type, and return the first one
var bands = ([30, 'Seconds', 'to', 'Mars', 1, 'Direction', true]);
function tinyString(collection) {
return collection.sort((a,b)=>typeof a === 'string' ? a.length-b.length:1).shift();
}
console.log( tinyString(bands) );