
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if String is a Combination of Strings in an Array using JavaScript
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
Advertisements