Get the longest and shortest string in an array JavaScript

We have an array of string literals like this −

const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',

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 −


const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
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]


The output in the console will be −

{ longest: 'sentence.', shortest: 'a' }