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. We'll track the maximum length and its index, updating when we find a longer string.

Syntax

function findLongestIndex(arr) {
    // Remove spaces and find longest string index
}

Example

const arr = ['Hello!', 'How are you', 'Can ', 'I use', 'splice method with', ' strings in Js?'];

const findLongestIndex = (arr) => {
    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));
4

How It Works

The function uses reduce() to iterate through the array. For each string:

  • Split by spaces: val.split(" ")
  • Join back without spaces: .join("")
  • Calculate length and compare with current maximum
  • Return index of first occurrence of maximum length

Alternative Approach Using Loop

const findLongestIndexLoop = (arr) => {
    let maxLength = 0;
    let maxIndex = 0;
    
    for (let i = 0; i  maxLength) {
            maxLength = lengthWithoutSpaces;
            maxIndex = i;
        }
    }
    
    return maxIndex;
};

const testArray = ['Hi there', 'JavaScript', 'Code', 'Programming language'];
console.log(findLongestIndexLoop(testArray));
3

Comparison

Method Approach Performance
reduce() Functional programming style Good for small arrays
for loop Traditional imperative style Slightly faster for large arrays

Conclusion

Both approaches effectively find the longest string index while excluding spaces. The reduce() method offers cleaner functional code, while the traditional loop provides slightly better performance for larger datasets.

Updated on: 2026-03-15T23:18:59+05:30

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements