【问题标题】:Finding shortest string in array查找数组中最短的字符串
【发布时间】:2017-06-21 08:02:20
【问题描述】:

我正在创建一个返回给定数组中最短字符串的函数。 如果有关系,它应该返回出现在给定数组中的第一个元素。期望给定的数组具有字符串以外的值。如果给定的数组是空的,它应该返回一个空字符串。如果给定的数组不包含字符串,它应该返回一个空字符串。

这是我的代码:

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) 检查数组是否有一些字符串。

【问题讨论】:

  • 减少签名是:reduce(function(current_result, current_item, current_index), initial_value)
  • 遍历数组,使用typeof检查值的类型。创建一个包含最短字符串的变量。假设要查找的第一个字符串为最短字符串,然后与找到的后续字符串进行比较。如果值比当前最短的字符串短,则仅替换。

标签: javascript arrays string


【解决方案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);

【讨论】:

  • 你能给我解释一下吗?我不懂箭头函数。
  • 哇。我真的很想知道为什么这个答案被否决了。是因为数组中有一个空字符串的边缘情况吗?你肯定没有想到这一点,亲爱的反对者?
【解决方案2】:

试试这个(重要的部分当然是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,因为这有点道理(如果你真的想要一个字符串作为结果,你仍然可以用空字符串做一个变通方法)

【讨论】:

  • 非字符串元素呢?
  • 在if语句中加一个类型条件
  • 其实我想到了如果数组中没有字符串就返回undefined,让我更新一下代码
【解决方案3】:
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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多