

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Forming and matching strings of an array based on a random string in JavaScript
Suppose, we have an array of strings that contains some names like this −
const arr = ['Dinesh', 'Mahesh', 'Rohit', 'Kamal', 'Jatin Sapru', 'Jai'];
And a random string of characters like this −
const str = 'lsoaakjm';
We are required to write a JavaScript function that takes in such an array and string as the two argument.
Then the function, for each element of the array should check whether that particular element can be formed completely from the string supplied as second argument.
If this condition satisfies for any element of the array, we should return that element otherwise we should return an empty string.
Example
Following is the code −
const arr = ['Dinesh', 'Mahesh', 'Rohit', 'Kamal', 'Jatin Sapru', 'Jai']; const str = 'lsoaakjm'; const initialise = (str = '', map) => { for(let i = 0; i < str.length; i++){ map[str[i]] = (map[str[i]] || 0) + 1; }; }; const deleteAll = map => { for(key in map){ delete map[key]; }; }; const checkForFormation = (arr = [], str = '') => { const map = {}; for(let i = 0; i < arr.length; i++){ const el = arr[i].toLowerCase(); initialise(str, map); let j; for(j = 0; j < el.length; j++){ const char = el[j]; if(!map[char]){ break; }else{ map[char]--; } }; if(j === el.length){ return arr[i]; }; deleteAll(map); } return ''; }; console.log(checkForFormation(arr, str));
Output
Following is the console output −
Kamal
- Related Questions & Answers
- Shuffling string based on an array in JavaScript
- Shifting string letters based on an array in JavaScript
- JavaScript filter an array of strings, matching case insensitive substring?
- Encrypting a string based on an algorithm in JavaScript
- Constructing a string based on character matrix and number array in JavaScript
- Modify an array based on another array JavaScript
- Filter an object based on an array JavaScript
- Encrypting a string based on an algorithm using JavaScript
- Forming string using 0 and 1 in JavaScript
- Order an array of words based on another array of words JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Splitting strings based on multiple separators - JavaScript
- Change string based on a condition - JavaScript
- Returning acronym based on a string in JavaScript
- Wildcard matching of string JavaScript
Advertisements