Find the shortest string in an array - JavaScript

We are required to write a JavaScript function that takes in an array of strings and returns the shortest string in the array. This is a common programming problem that can be solved efficiently using different approaches.

We will explore multiple methods to find the shortest string, from simple loops to functional programming approaches.

Using for Loop

The most straightforward approach uses a for loop to iterate through the array and track the shortest string:

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];

function findShortestString(strings) {
    if (strings.length === 0) return '';
    
    let shortest = strings[0];
    
    for (let i = 1; i 

be

Using Array.reduce() Method

The reduce() method provides a functional programming approach to find the shortest string:

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];

const findShortest = strings => {
    return strings.reduce((shortest, current) => {
        return current.length 

be

Finding Index of Shortest String

If you need the index rather than the string itself, here's how to modify the approach:

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];

const findShortestIndex = strings => {
    const result = strings.reduce((acc, val, index) => {
        let { ind, len } = acc;
        if (val.length 

Index: 2
String: be

Using Math.min() with Spread Operator

For a more concise approach, combine Math.min() with array methods:

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];

const findShortestWithMath = strings => {
    const minLength = Math.min(...strings.map(str => str.length));
    return strings.find(str => str.length === minLength);
};

console.log(findShortestWithMath(arr));
be

Handling Edge Cases

Always consider edge cases like empty arrays or arrays with empty strings:

function findShortestSafe(strings) {
    if (!strings || strings.length === 0) {
        return null; // or throw an error
    }
    
    return strings.reduce((shortest, current) => {
        return current.length 

null

pie

Comparison

Method Performance Readability Returns
for loop Fastest High String
reduce() Good High String/Index
Math.min() + find() Slower (two passes) Very High String

Conclusion

Use the for loop approach for best performance, or reduce() for functional style programming. Always handle edge cases like empty arrays to make your code robust.

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

778 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements