Find char combination in array of strings JavaScript


We have to write a function that accepts an array of strings and a string. Our job is to check whether the array contains any sequence or subsequence of the string as its element or not, and the function should return a boolean based on this fact.

For instance −

const x = 'ACBC';
const arr = ['cat','AB'];
const arr2 = ['cat','234','C'];
const arr3 = ['cat','CC'];
const arr4 = ['cat','BB'];
console.log(containsString(arr,x)) // true
console.log(containsString(arr2,x)) // true
console.log(containsString(arr3,x)) // true
console.log(containsString(arr4,x)) // false

Therefore, let’s write the code for this function −

Example

const x = 'ACBC';
const arr = ['cat','AB'];
const arr2 = ['cat','234','C'];
const arr3 = ['cat','CC'];
const arr4 = ['cat','BB'];
const splitSort = function(){
   return this.split("").sort().join("");
};
String.prototype.splitSort = splitSort;
const containsString = (arr, str) => {
   const sorted = str.splitSort();
   for(let i = 0; i < arr.length; i++){
      const sortedEl = arr[i].splitSort();
      if(sorted.includes(sortedEl)){
         return true;
      }
   };
   return false;
}
console.log(containsString(arr,x)) // true
console.log(containsString(arr2,x)) // true
console.log(containsString(arr3,x)) // true
console.log(containsString(arr4,x)) // false

Output

The output in the console will be −

true
true
true
false

Updated on: 25-Aug-2020

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements