Get the longest and shortest string in an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have an array of string literals like this −

const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];

We are required to write a function that returns the longest and the shortest word from this array. We will use Array.prototype.reduce() method to keep track of the longest and shortest word in the array through a complete iteration.

The code for this will be −

Example

const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
const findWords = (arr) => {
   return arr.reduce((acc, val) => {
      const { length: len } = val;
      if(len > acc['longest']['length']){
         acc['longest'] = val;
      }else if(len < acc['shortest']['length']){
         acc['shortest'] = val;
      };
      return acc;
   }, {
      longest: arr[0],
      shortest: arr[0]
   });
};
console.log(findWords(arr));

Output

The output in the console will be −

{ longest: 'sentence.', shortest: 'a' }
raja
Updated on 24-Aug-2020 05:47:08

Advertisements