Javascript 查找数组中最长的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6521245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding longest string in array
提问by Neir0
Is there a short way to find the longest string in a string array?
有没有一种方法可以在字符串数组中找到最长的字符串?
Something like arr.Max(x => x.Length);
?
像arr.Max(x => x.Length);
什么?
回答by deceze
var longest = arr.sort(function (a, b) { return b.length - a.length; })[0];
Probably more efficient, but only available since Javascript 1.8/ECMAScript 5and not available by default in older browsers:
可能更有效,但仅自Javascript 1.8/ECMAScript 5 起可用,默认情况下在旧浏览器中不可用:
var longest = arr.reduce(function (a, b) { return a.length > b.length ? a : b; });
回答by Dávid Veszelovszki
A new answer to an old question: in ES6 you can do shorter:
一个老问题的新答案:在 ES6 中,你可以做得更短:
Math.max(...(x.map(el => el.length)));
回答by Jason Gennaro
I would do something like this
我会做这样的事情
var arr = ['first item', 'second item is longer than the third one',
'third longish item'];
var lgth = 0;
var longest;
for(var i=0; i < arr.length; i++){
if(arr[i].length > lgth){
var lgth = arr[i].length;
longest = arr[i];
}
}
alert(longest);
回答by katspaugh
var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];
回答by mplungjan
Using Array.prototype - (sort is similar to what was posted by @katsPaugh and @deceze while I was doing a fiddle)
使用 Array.prototype - (排序类似于@katsPaugh 和@deceze 在我做小提琴时发布的内容)
DEMO HERE
演示在这里
var arr = [
"2 --",
"3 ---",
"4 ----",
"1 -",
"5 -----"
];
Array.prototype.longest=function() {
return this.sort(
function(a,b) {
if (a.length > b.length) return -1;
if (a.length < b.length) return 1;
return 0
}
)[0];
}
alert(arr.longest());
回答by Niels van Reijmersdal
Maybe not the fastest, but certainly pretty readable:
也许不是最快的,但肯定非常可读:
function findLongestWord(array) {
var longestWord = "";
array.forEach(function(word) {
if(word.length > longestWord.length) {
longestWord = word;
}
});
return longestWord;
}
var word = findLongestWord(["The","quick","brown", "fox", "jumped", "over", "the", "lazy", "dog"]);
console.log(word); // result is "jumped"
The array function forEach has been supported since IE9+.
从 IE9+ 开始支持数组函数forEach。
回答by Giancarlo Ventura
I see the shortest solution
我看到最短的解决方案
function findLong(s){
return Math.max.apply(null, s.split(' ').map(w => w.length));
}
回答by Matías Fidemraizer
I provide a functional+recursive approach. See comments to understand how it works:
我提供了一个函数+递归的方法。查看评论以了解它是如何工作的:
const input1 = ['a', 'aa', 'aaa']
const input2 = ['asdf', 'qwer', 'zxcv']
const input3 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf']
const input4 = ['ddd', 'dddddddd', 'dddd', 'ddddd', 'ddd', 'dd', 'd', 'd', 'dddddddddddd']
// Outputs which words has the greater length
// greatestWord :: String -> String -> String
const greatestWord = x => y =>
x.length > y.length ? x : y
// Recursively outputs the first longest word in a series
// longestRec :: String -> [String] -> String
const longestRec = longestWord => ([ nextWord, ...words ]) =>
// ^^^^^^^^^^^^
// Destructuring lets us get the next word, and remaining ones!
nextWord // <-- If next word is undefined, then it won't recurse.
? longestRec (greatestWord (nextWord) (longestWord)) (words)
: longestWord
// Outputs the first longest word in a series
// longest :: [String] -> String
const longest = longestRec ('')
const output1 = longest (input1)
const output2 = longest (input2)
const output3 = longest (input3)
const output4 = longest (input4)
console.log ('output1: ', output1)
console.log ('output2: ', output2)
console.log ('output3: ', output3)
console.log ('output4: ', output4)
回答by Alexander Lomia
In ES6 this could be accomplished with a reduce()
call in O(n)
complexity as opposed to solutions using sort()
which is O(nlogn)
:
在 ES6 中,这可以通过reduce()
调用O(n)
复杂性来完成,而不是使用sort()
which 的解决方案O(nlogn)
:
const getLongestText = (arr) => arr.reduce(
(savedText, text) => (text.length > savedText.length ? text : savedText),
'',
);
console.log(getLongestText(['word', 'even-longer-word', 'long-word']))
回答by Timo K?hk?nen
I was inspired of Jason's function and made a little improvements to it and got as a result rather fast finder:
我受到 Jason 功能的启发并对其进行了一些改进,结果获得了相当快的查找器:
function timo_longest(a) {
var c = 0, d = 0, l = 0, i = a.length;
if (i) while (i--) {
d = a[i].length;
if (d > c) {
l = i; c = d;
}
}
return a[l];
}
arr=["First", "Second", "Third"];
var longest = timo_longest(arr);
Speed results: http://jsperf.com/longest-string-in-array/7