Check if the string is a combination of strings in an array using JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of strings as the first argument and a string as the second argument.

The function should check whether the string specified by second argument can be formed by combining the strings of the array in any possible way.

For example − If the input array is −

const arr = ["for","car","keys","forth"];

And the string is −

const str = "forthcarkeys";

Then the output should be true, because the string is a combination of elements at 3, 1 and 2 indexes of the array.

Example

The code for this will be −

const arr = ["for","car","keys","forth"];
const str = "forthcarkeys";
const checkPossibility = (str = '', arr = []) => {
   let possibilities = arr.reduce(function (r, a) {
      let p = str.indexOf(a);
      while (p !== −1) {
         r.push({ word: a, position: p });
         p = str.indexOf(a, p + 1);
      }
      return r;
   }, []);
   const findRecursively = (i, t) => {
      let s = t.slice(), j;
      if (i === possibilities.length) {
         return !t.join('');
      }
      if (possibilities[i].word.split('').every(function (c, j) {
         return
         s[j + possibilities[i].position] !== ''; })) {
         for (j = 0; j < possibilities[i].word.length; j++) {
            s[j + possibilities[i].position] = '';
         }
      }
      return findRecursively(i + 1, s) || findRecursively(i + 1, t);
   }
   return findRecursively(0, str.split(''));
};
console.log(checkPossibility(str, arr));

Output

And the output in the console will be −

true
raja
Published on 24-Nov-2020 06:57:16
Advertisements