查找数组中最长的字符串

在字符串数组中找到最长的字符串有一个简短的方法吗?

arr.Max(x => x.Length);之类的?

173354 次浏览

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];
}
}


console.log(longest);

var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];

Available since Javascript 1.8/ECMAScript 5 and available in most older browsers:

var longest = arr.reduce(
function (a, b) {
return a.length > b.length ? a : b;
}
);

Otherwise, a safe alternative:

var longest = arr.sort(
function (a, b) {
return b.length - a.length;
}
)[0];

I was inspired of Jason's function and made a little improvements to it and got as a result rather fast finder:

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

I would do something like this:

function findLongestWord(str) {
var array = str.split(" ");
var maxLength=array[0].length;
for(var i=0; i < array.length; i++ ) {
if(array[i].length > maxLength) maxLength = array[i].length
}
return maxLength;
}


findLongestWord("What if we try a super-long word such as otorhinolaryngology");

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+.

I see the shortest solution

function findLong(s){
return Math.max.apply(null, s.split(' ').map(w => w.length));
}

A new answer to an old question: in ES6 you can do shorter:

Math.max(...(x.map(el => el.length)));

If your string is already split into an array, you'll not need the split part.

function findLongestWord(str) {
str = str.split(' ');
var longest = 0;


for(var i = 0; i < str.length; i++) {
if(str[i].length >= longest) {
longest = str[i].length;
}
}
return longest;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

In case you expect more than one maximum this will work:

_.maxBy(Object.entries(_.groupBy(x, y => y.length)), y => parseInt(y[0]))[1]

It uses lodash and returns an array.

With ES6 and it support a duplicate string

var allLongestStrings = arrayOfStrings => {
let maxLng = Math.max(...arrayOfStrings.map( elem => elem.length))
return arrayOfStrings.filter(elem => elem.length === maxLng)
}


let arrayOfStrings = ["aba", "aa", "ad", "vcd","aba"]
 

console.log(allLongestStrings(arrayOfStrings))

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)

In ES6 this could be accomplished with a reduce() call in O(n) complexity as opposed to solutions using sort() which is O(nlogn):

const getLongestText = (arr) => arr.reduce(
(savedText, text) => (text.length > savedText.length ? text : savedText),
'',
);


console.log(getLongestText(['word', 'even-longer-word', 'long-word']))

Modern browsers support a for...of loop. The fastest and shortest way to solve this problem in Chrome, Safari, Edge, and Firefox is also the clearest:

let largest = '';
for (let item of arr) {
if (item.length > largest.length) largest = item
}

In IE, you can use Array.forEach; that's still faster and clearer than sorting or reducing the array.

var largest = '';
arr.forEach(function(item) {
if (item.length > largest.length) largest = item
});
function max( input ) {
return input.reduce((a, b) => a.length <= b.length ? b : a)
}

If you want to know the INDEX of the longest item:

var longest = arr.reduce(
(a, b, i) => arr[a].length < b.length ? i : a,
0
);

(which can be a one-liner for those that love that stuff.... but it's split up here for readabilty)