在数组中查找最短的字符串

时间:2017-06-21 08:02:21

标签: javascript arrays string

我正在创建一个返回给定数组中最短字符串的函数。 如果存在tie,则应返回第一个元素以显示在给定数组中。期望给定数组具有除字符串之外的值。如果给定数组为空,则应返回空字符串。如果给定的数组不包含任何字符串,则应该返回一个空字符串。

这是我的代码:

function findShortestWordAmongMixedElements(arr) {
  if(arr.length === 0 && arr.indexof(arr)){
    return '';
  } else{
   return arr.reduce(function(a, b) {
      return a.length >= b.length ? a : b;
    })
  }      
}

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

而不是两个,它返回三个。另外arr.indexof(arr)检查数组是否有一些字符串。

3 个答案:

答案 0 :(得分:1)

这应该涵盖您的要求:

let array = [4, 'two', 2, 'three'];
let shortest = array.filter(v => typeof v === 'string')
                    .reduce((a, v) => a && a.length <= v.length ? a : v, '');

console.log(shortest);

答案 1 :(得分:0)

试试这个(重要的部分当然是reduce):

var arr = ["a", 1, "ab", "ac", 4, "ade", "ac" ] ;

var short = arr.filter( (e)=> typeof e == 'string' ).reduce( (res, elem, index)=>{
  if(res==undefined || res.length>elem.length)
    res = elem;
  return res;
}, undefined );

alert(short) 

它的作用如下:   它过滤数组只保留字符串,如果res未定义或者res的长度大于元素的长度,那么我们将元素存储在res中。

因此,适应您的问题:

function findShortestWordAmongMixedElements(arr) {
  if(arr.length === 0 && arr.indexof(arr)){
    return undefined; 
  } else {
    return arr.filter( (e)=> typeof e == 'string' ).reduce( (res, elem, index)=>{
      if(res==undefined || res.length>elem.length)
        res = elem;
      return res;
    }, undefined );
  }
}

注意:如果数组中没有字符串,我决定返回undefined,因为它有点意义(如果你真的想要一个字符串作为结果,你仍然可以使用空字符串进行解决方法)

答案 2 :(得分:-1)

function findShortestWordAmongMixedElements(arr) {
  if(arr.length === 0 && arr.indexof(arr)){
    return '';
  } else{
   return arr.reduce(function(a, b) {
      return a.length >= toString(b).length ? toString(b) : a;
    },"");
  }      
}

var output = findShortestWordAmongMixedElements([4, 'two', 2, 'three']);
console.log(output);
相关问题