Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding longest string in array

Tags:

javascript

Is there a short way to find the longest string in a string array?

Something like arr.Max(x => x.Length);?

like image 718
Neir0 Avatar asked Jun 29 '11 13:06

Neir0


People also ask

How do you find the longest string in an array C++?

I wrote this code: char a[100][100] = {"solol","a","1234567","123","1234"}; int max = -1; for(int i=0;i<5;i++) if(max<strlen(a[i])) max=strlen(a[i]); cout<<max; The output it gives is -1. But when I initialize the value of max by 0 instead of 1, the code works fine.

How do you find the longest string in an array in Python?

Use Python's built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.


1 Answers

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]; 
like image 58
deceze Avatar answered Sep 29 '22 06:09

deceze