找到数组中最短的字符串

时间:2016-11-29 11:34:21

标签: javascript arrays

如何在javascript数组中找到具有不同数组元素数的最短字符串? 我用了

var min = Math.min(arr[0].length,arr[1].length,arr[2].length);

我的结果就像是3个数组元素之间的最短字符串。但我不想关心元素的数量

5 个答案:

答案 0 :(得分:9)

使用Array#reduce方法。

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  })
)

ES6 arrow function

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce((a, b) => a.length <= b.length ? a : b)
)

答案 1 :(得分:7)

使用Array#map创建长度数组,然后将其应用于Math.min()

&#13;
&#13;
.tab-pane > .tab-header-area > .headers-region > .tab {
      -fx-shape: "M300,290 L310,168 L410,168 L421,290 L300,290 z";
}

.tab-pane:focused > .tab-header-area > .headers-region > .tab:selected .focus-indicator {
    -fx-shape: "M300,290 L310,168 L410,168 L421,290 L300,290 z";
}   
&#13;
&#13;
&#13;

或使用ES6&#39;} array spread和箭头功能:

&#13;
&#13;
var arr = ['cats', 'giants', 'daughters', 'ice'];
var min = Math.min.apply(Math, arr.map(function(str) { return str.length; }));
console.log(min);
&#13;
&#13;
&#13;

答案 2 :(得分:3)

您可以使用const arr = ['small', 'big', 'yuge'] const shorter = (left, right) => left.length <= right.length ? left : right console.log( arr.reduce(shorter) )

{{1}}

答案 3 :(得分:0)

您可以将Math.minArray#reduce一起使用。

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(r, a) {
    return Math.min(r, a.length);
  }, Infinity)
);

ES6

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(arr.reduce((r, a) => Math.min(r, a.length), Infinity));

答案 4 :(得分:-2)

请参阅下面的简短解决方案。我希望它有所帮助:

var arr = ['cats', 'giants', 'daughters', 'ice'];    
arr.sort(); // ice, cats, giants, daughters
var shortest_element = arr[0]; // ice