Finding longest string in array

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

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


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

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

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

Tags:

Javascript