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

Updated on: 22-Jan-2021

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements