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 last.

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' ]

Updated on: 24-Nov-2020

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements