How to find and print the common characters (letters) in different strings with Node.js

2 Answers

0 votes
function getCommonCharacters(str1, str2) {
    let strcommon = "";
     
    for (let i in str1) {
        if (str2.includes(str1[i])) {
            if (! strcommon.includes(str1[i])) {
                strcommon += str1[i];
            }
        }
    }
     
    return strcommon;
}
 
const str1 = "c c++ c# java go python";
const str2 = "nodejs php javascript";
 
let strcommon = getCommonCharacters(str1, str2);
 
console.log("Same letters are: " + strcommon);
 
 
 
  
/*
run:
   
Same letters are: c javopthn
   
*/

 



answered Jan 27, 2024 by avibootz
0 votes
function getCommonCharacters(str1, str2) {
    let set1 = new Set(str1);
    let set2 = new Set(str2);
    
    let strcommon = new Set([...set1].filter(x => set2.has(x)));
     
    return [...strcommon].join('');;
}
 
const str1 = "c c++ c# java go python";
const str2 = "nodejs php javascript";
 
let strcommon = getCommonCharacters(str1, str2);
 
console.log("Same letters are: " + strcommon);
 
 
 
  
/*
run:
   
Same letters are: c javopthn
   
*/

 



answered Jan 27, 2024 by avibootz
...