JavaScript中基于随机字符串形成和匹配数组的字符串
假设,我们有一个字符串数组,其中包含一些这样的名称-
const arr = ['Dinesh', 'Mahesh', 'Rohit', 'Kamal', 'Jatin Sapru', 'Jai'];
和这样的随机字符串-
const str = 'lsoaakjm';
我们需要编写一个JavaScript函数,它接受这样一个数组和字符串作为两个参数。
然后,对于数组的每个元素,函数应该检查该特定元素是否可以完全由作为第二个参数提供的字符串构成。
如果该条件满足数组中的任何元素,我们应该返回该元素,否则我们应该返回一个空字符串。
示例
以下是代码-
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));输出结果以下是控制台输出-
Kamal