We are required to write a JavaScript function that takes in two strings, let us say str1 and str2.
The function should count the number of common characters that exist in the strings.
For example −
const str1 = 'aabbcc'; const str2 = 'adcaa';
Then the output should be 3
Example
Following is the code −
const str1 = 'aabbcc';
const str2 = 'adcaa';
const commonCharacterCount = (str1 = '', str2 = '') => {
let count = 0;
str1 = str1.split('');
str2 = str2.split('');
str1.forEach(e => {
if (str2.includes(e)) {
count++;
str2.splice(str2.indexOf(e), 1);
};
});
return count;
};
console.log(commonCharacterCount(str1, str2));Output
Following is the output on console −
3