How to get the number of characters that two strings have in common in Node.js

1 Answer

0 votes
function commonCharactersCount(str1, str2) {
    // Convert strings to sets of characters
    const set1 = new Set(str1);
    const set2 = new Set(str2);

    // Find the intersection of the two sets
    let count = 0;
    for (const char of set1) {
        if (set2.has(char)) {
            count++;
        }
    }

    return count;
}

const str1 = "abcdefghi";
const str2 = "xayhzgoe";

console.log(commonCharactersCount(str1, str2)); 


      
/*
run:
      
4
      
*/

 



answered Mar 20 by avibootz
...