如何在具有混合数据类型的数组中返回最短字符串?

时间:2017-01-22 17:54:35

标签: javascript arrays string

任务是返回具有混合数据类型的数组中的最短字符串,例如,如果我们有以下数组:

var arr1 = [1,9," word1"," elephant",5," go",19];

我需要这么说#34;去"归还。

我有这个代码,但我需要一种方法,我不必声明超长字符串:D就像我在这里做的那样:

var word = "SuperSuperLongLooooooongLooooooooooongVeryLoooooooooooongString";

function findShortestWordAmongMixedElements(arr) {
// your code here
if (arr[0] === undefined){

      return "";

  }
 for (var x = 0; x < arr.length; x++){
  if (typeof arr[x] === "string" && arr[x].length < word.length){

      word = arr[x];

  } 

 }

 if (word.length === 0){

      return "";

  }
 return word;
}

findShortestWordAmongMixedElements([4, 'two', 2, 'three']); // returns "two"

还有一些额外的任务,例如检查数组是否为空以及其他一些小位,以防你想知道为什么代码中有额外的东西。

欢迎任何帮助。谢谢。

编辑:

谢谢大家,它按照预期的那样工作。

5 个答案:

答案 0 :(得分:2)

您可以使用Array#reduce并返回最小的字符串。

var array = [1, 9, "word1", "elephant", 5, "go", 19],
    result = array.reduce(function (r, a) {
        return typeof a !== 'string' || r !== undefined && r.length < a.length ? r : a;
    }, undefined);

console.log(result);

答案 1 :(得分:2)

您可以使用 Array.filter()删除非字符串元素,并使用 Array.sort()在第一个位置删除最短元素:

&#13;
&#13;
var arr1 = [1,9,"word1", "elephant", 5, "go", 19];
var result = arr1.filter(x => isNaN(x)).sort((a,b) => a.length - b.length)[0];
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

将您找到的第一个字符串作为单词

如果你发现另一个字符串检查它是否更短&gt;&gt;&gt;用较短的一个替换单词

其他&gt;&gt;&gt;检查下一步

答案 3 :(得分:1)

使用filterreduce,假设您可以使用ES6的箭头功能,这将有效:

arr1.filter(x => typeof x === 'string').reduce((shortest, x) => shortest === null || x.length < shortest.length ? x : shortest , null);

解释如何:

.filter(x => typeof x === 'string')过滤数组并返回所有字符串。

.reduce((shortest, x) => ..., null)对每个项应用一个函数,修改每个传递的shortest参数。在第一次传递时,null的值为shortest,在上述代码的情况下,如果当前x,则使用当前shortest的值nullx短于shortest

答案 4 :(得分:0)

所以这是我的伪代码: let someArr = ['tiger', 'lion', 1, 'cat', 3, 4, 'horse', 'takin']; 1. if (!someArr.length) return ''; 2. var newArr = someArr.filter(fn(elem) => return typeof elem === 'string')); 3. if (!newArr.length) return ''; 4. newArr.filter(fn(acc,curr) => acc.length > curr.length ? acc : curr) Output: cat

*Explanation* 1. Check if the array is empty. If it is then return an empty string: 2. Use the filter function to filter out only the values that are string and store it in a different variable. 3. Check if the new array is also empty. If it doesn't then return an empty string (this is make sure if the original array had no string values, or only had integers). 4. Take this new array and apply the reduce function to get the shortest string.