javascript - 数组链接,按原语类型过滤数组并返回最短长度元素

标签 javascript arrays typeof chain

我尝试从充满不同类型基元的数组中提取最短的字符串,但失败了。我究竟做错了什么?还有其他的吗

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'

最佳答案

您可以按长度和类型排序,并返回第一个

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) );

关于javascript - 数组链接,按原语类型过滤数组并返回最短长度元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711234/

相关文章:

javascript - Normalizr - 未达到预期结果

javascript - 如何使用编辑器更改选择列表

php - 非法字符串偏移 'name' php - 许多数组变成 1 个数组

JavaScript:意外的类型结果

c++ - boost::mpl::integral_c 之类的模板可以注册到 Boost.Typeof 吗?

javascript - Angular JS : Toggle Only One Item at a Time

javascript - 反向数组函数在 javascript 中不起作用

javascript - 您的所有断言都通过了吗?

javascript - 如何判断它是对象还是数组?

javascript - 为什么我的 NextJS 代码会运行多次,如何避免?