Finding all the longest strings from an array in JavaScript



Suppose, we have an array of strings like this −

const arr = [
   'iLoveProgramming',
   'thisisalsoastrig',
   'Javascriptisfun',
   'helloworld',
   'canIBeTheLongest',
   'Laststring'
];

We are required to write a JavaScript function that takes in one such array of strings. The purpose of our function is to pick all the longest string (if there are more than one).

The function should finally return an array of all the longest strings in the array.

Example

Following is the code −

const arr = [
   'iLoveProgramming',
   'thisisalsoastrig',
   'Javascriptisfun',
   'helloworld',
   'canIBeTheLongest',
   'Laststring'
];
const getLongestStrings = (arr = []) => {
   return arr.reduce((acc, val, ind) => {
      if (!ind || acc[0].length < val.length) {
         return [val];
      }
      if (acc[0].length === val.length) {
         acc.push(val);
      }
      return acc;
   }, []);
};
console.log(getLongestStrings(arr));

Output

Following is the output on console −

[ 'iLoveProgramming', 'thisisalsoastrig', 'canIBeTheLongest' ]

Advertisements