98 votes

Trouver la chaîne la plus longue dans le tableau

Existe-t-il un moyen rapide de trouver la chaîne la plus longue dans un tableau de chaînes ?

Quelque chose comme arr.Max(x => x.Length); ?

220voto

deceze Points 200115

Disponible depuis Javascript 1.8/ECMAScript 5 et disponible dans la plupart des navigateurs plus anciens :

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

Sinon, une alternative sûre :

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

47voto

Une nouvelle réponse à une vieille question : dans ES6, vous pouvez faire plus court :

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

29voto

Jason Gennaro Points 20848

je ferais quelque chose comme ça

 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);

5voto

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

4voto

mplungjan Points 36458

Utilisation de Array.prototype - (le tri est similaire à ce qui a été posté par @katsPaugh et @deceze pendant que je faisais du violon)

DÉMO ICI

 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());    

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X