I have an array of strings. A user typed “ztaf”. How can I use JavaScript to find which of the letters the user typed match somewhere in the array? The answer should be “taf”.
var array = [ "tofu", "fish", "meat" ];
var user_type = "ztaf";
var found = ""; // It should be "taf".
I have tried it, but it keeps saying there is no match.
CodePudding user response:
You can achieve this by using String.split()
along with the Array.filter()
, Array.join()
and String.includes()
methods.
Live Demo :
var array = ["tofu","fish","meat"];
var user_type = "ztaf";
var found = user_type.split('').filter(char => array.join().includes(char));
console.log(found.join(''));
CodePudding user response:
if array is a string then you can convert it into array using json parse
array = JSON.parse(array) // this will convert it into array
// here comes the actual code =>
var array = '\["tofu", "fish", "meat"\]'
var user_type = 'ztaf'
array = JSON.parse(array)
console.log(array)
found = ''
for (let i = 0; i < user_type.length; i ) { if(array.some(elem=>elem.contains(user_type[i]))) found =user_type[i]
}