- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements