Find longest string in array (excluding spaces) JavaScript


We are required to write a function that accepts an array of string literals and returns the index of the longest string in the array. While calculating the length of strings we don’t have to consider the length occupied by whitespaces

If two or more strings have the same longest length, we have to return the index of the first string that does so.

We will iterate over the array, split each element by whitespace, join again and calculate the length, after this we will store this in an object. And when we encounter length greater than currently stored in the object, we update it and lastly, we return the index.

Example

const arr = ['Hello!', 'How are you', 'Can ', 'I use', 'splice method
with', ' strings in Js?'];
const findLongestIndex = (arr) => {
   const index = {
   '0': 0
};
const longest = arr.reduce((acc, val, index) => {
   const actualLength = val.split(" ").join("").length;
   if(actualLength > acc.length){
      return {
         index,
         length: actualLength
      };
   }
   return acc;
   }, {
      index: 0,
      length: 0
   });
   return longest.index;
};
console.log(findLongestIndex(arr));

Output

The output in the console will be −

4

Updated on: 20-Aug-2020

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements