Finding longest string in array

Javascript

Javascript Problem Overview


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

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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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']))

Solution 7 - Javascript

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)

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

I see the shortest solution

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Solution 14 - Javascript

function max( input ) {
return input.reduce((a, b) => a.length <= b.length ? b : a)
}

Solution 15 - Javascript

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)

Solution 16 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeir0View Question on Stackoverflow
Solution 1 - JavascriptdecezeView Answer on Stackoverflow
Solution 2 - JavascriptDavid VeszelovszkiView Answer on Stackoverflow
Solution 3 - JavascriptJason GennaroView Answer on Stackoverflow
Solution 4 - JavascriptNiels van ReijmersdalView Answer on Stackoverflow
Solution 5 - JavascriptkatspaughView Answer on Stackoverflow
Solution 6 - JavascriptAlex LomiaView Answer on Stackoverflow
Solution 7 - JavascriptMatías FidemraizerView Answer on Stackoverflow
Solution 8 - JavascriptTimo KähkönenView Answer on Stackoverflow
Solution 9 - JavascriptSiawash KasraView Answer on Stackoverflow
Solution 10 - JavascriptGiancarlo VenturaView Answer on Stackoverflow
Solution 11 - JavascriptAndy SmithView Answer on Stackoverflow
Solution 12 - JavascriptGismo RanasView Answer on Stackoverflow
Solution 13 - JavascriptTaha AzzabiView Answer on Stackoverflow
Solution 14 - JavascriptmodosView Answer on Stackoverflow
Solution 15 - JavascriptlowcrawlerView Answer on Stackoverflow
Solution 16 - JavascriptDan FabulichView Answer on Stackoverflow