Find all substrings combinations within arrays in JavaScript

We are required to write a JavaScript function that takes in an array of strings. The function should find all the substring and superstring combinations that exist in the array and return an array of those elements.

For example ? If the array is ?

const arr = ["abc", "abcd", "abcde", "xyz"];

Then the output should be ?

const output = ["abc", "abcd", "abcde"];

because the first two are the substring of the last one.

How It Works

The algorithm compares each string with every other string in the array. If one string is found as a substring of another (or vice versa), both strings are marked as part of a combination. The function uses an object to track which strings participate in substring relationships.

Example

The code for this will be ?

const arr = ["abc", "abcd", "abcde", "xyz"];

const findStringCombinations = (arr = []) => {
    let i, j, res = {};
    for (i = 0; i < arr.length - 1; i++) {
        if (res[arr[i]]) {
            continue;
        };
        for (j = i + 1; j < arr.length; j++) {
            if (res[arr[j]]) {
                continue;
            }
            if (arr[i].indexOf(arr[j]) !== -1 || arr[j].indexOf(arr[i]) !== -1) {
                res[arr[i]] = true;
                res[arr[j]] = true;
            }
        };
    };
    const result = arr.filter(el => res[el]);
    return result;
};

console.log(findStringCombinations(arr));

Output

And the output in the console will be ?

[ 'abc', 'abcd', 'abcde' ]

Alternative Approach Using includes()

Here's a more modern approach using the includes() method:

const arr2 = ["hello", "world", "helloworld", "test"];

const findCombinationsModern = (arr = []) => {
    const combinations = new Set();
    
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length; j++) {
            if (i !== j) {
                if (arr[i].includes(arr[j]) || arr[j].includes(arr[i])) {
                    combinations.add(arr[i]);
                    combinations.add(arr[j]);
                }
            }
        }
    }
    
    return Array.from(combinations);
};

console.log(findCombinationsModern(arr2));
[ 'hello', 'helloworld' ]

Key Points

  • The function identifies strings that have substring/superstring relationships with other strings in the array
  • Both indexOf() and includes() methods can be used to check substring existence
  • The algorithm has O(n²) time complexity due to nested loops
  • Using a Set in the modern approach automatically handles duplicates

Conclusion

This function efficiently finds all strings in an array that participate in substring relationships. The modern approach using includes() and Set provides cleaner, more readable code while achieving the same result.

Updated on: 2026-03-15T23:19:00+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements