[javascript] Finding longest string in array

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

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

This question is related to javascript

The answer is


Using Array.prototype - (sort is similar to what was posted by @katsPaugh and @deceze while I was doing a fiddle)

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

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 provide a functional+recursive approach. See comments to understand how it works:

_x000D_
_x000D_
const input1 = ['a', 'aa', 'aaa']_x000D_
const input2 = ['asdf', 'qwer', 'zxcv']_x000D_
const input3 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf']_x000D_
const input4 = ['ddd', 'dddddddd', 'dddd', 'ddddd', 'ddd', 'dd', 'd', 'd', 'dddddddddddd']_x000D_
_x000D_
// Outputs which words has the greater length_x000D_
// greatestWord :: String -> String -> String_x000D_
const greatestWord = x => y => _x000D_
      x.length > y.length ? x : y_x000D_
      _x000D_
// Recursively outputs the first longest word in a series_x000D_
// longestRec :: String -> [String] -> String_x000D_
const longestRec = longestWord => ([ nextWord, ...words ]) =>_x000D_
      //                                ^^^^^^^^^^^^_x000D_
      // Destructuring lets us get the next word, and remaining ones!_x000D_
      nextWord // <-- If next word is undefined, then it won't recurse._x000D_
        ? longestRec (greatestWord (nextWord) (longestWord)) (words) _x000D_
        : longestWord_x000D_
_x000D_
_x000D_
// Outputs the first longest word in a series_x000D_
// longest :: [String] -> String_x000D_
const longest = longestRec ('')_x000D_
_x000D_
const output1 = longest (input1)_x000D_
const output2 = longest (input2) _x000D_
const output3 = longest (input3)_x000D_
const output4 = longest (input4)_x000D_
_x000D_
console.log ('output1: ', output1)_x000D_
console.log ('output2: ', output2)_x000D_
console.log ('output3: ', output3)_x000D_
console.log ('output4: ', output4)
_x000D_
_x000D_
_x000D_


Came here for the solution, but could not understand much, posting my version;

const getLongestStr = (longestStr, str) => {
  return longestStr.length > str.length ? longestStr : str;
}
var input = ['ali', 'Shahenshah', 'naqvi', 'hm'];
var longest = input.reduce(getLongestStr, "")

function allLongestStrings(array) {
    const newArr=[];
    let temp =    Math.max(...(array.map(el => el.length)));    
     array.forEach(item => {
        if(temp == item.length){
          newArr.push(item);
        }
    });
    return newArr;
}

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

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

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

function findLongestWord(str) {
  str = str.split(" ");
  var sorted = str.sort(function(prev,current){
    return prev.length - current.length;   
  });
  var index = sorted.length;
  str = sorted[index-1];
  return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

var longest = (arr) => {
  let sum = 0
  arr.map((e) => {
    sum = e.length > sum ? e.length : sum
  })
  return sum
}

it can be work


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

I would do something like this

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


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 ES6 this could be accomplished with a reduce() call in O(n) complexity as opposed to solutions using sort() which is O(nlogn):

_x000D_
_x000D_
const getLongestText = (arr) => arr.reduce(_x000D_
  (savedText, text) => (text.length > savedText.length ? text : savedText),_x000D_
  '',_x000D_
);_x000D_
_x000D_
console.log(getLongestText(['word', 'even-longer-word', 'long-word']))
_x000D_
_x000D_
_x000D_


I see the shortest solution

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

With ES6 supported also 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))

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


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.


This is my simple solution

var arr = ["you", "are", "the", "love", "of", "my", "life"];
var sorted = arr.sort(function (a, b){
     return b.length - a.length;
});

console.log(sorted[0])

I will 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");

var array = ["hello","falsey","undefined"];
var findLongestWord = function(array){
    var longest = array.reduce(function(a,b){
    return (a.length > b.length) ? a : b;
  });
    return longest;
}
findLongestWord(array);