Find all substrings combinations within arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Published on 24-Nov-2020 09:54:09
Advertisements