Find the Smallest element from a string array in JavaScript



We are required to write a JavaScript function that takes in an array of strings and returns the index of string that is shortest in length.

We will simply use a for loop and persist the index of string which is shortest in length.

Therefore, let’s write the code for this function βˆ’

Example

The code for this will be βˆ’

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];
const findSmallest = arr => {
   const creds = arr.reduce((acc, val, index) => {
      let { ind, len } = acc;
      if(val.length < len){
         len = val.length;
         ind = index;
      };
      return { ind, len };
   }, {
      ind: -1,
      len: Infinity
   });
   return arr[creds['ind']];
};
console.log(findSmallest(arr));

Output

The output in the console will be βˆ’

be
Updated on: 2020-10-22T12:46:07+05:30

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements