I have tried the codes below. However, I do not know how to remove the duplicate characters. Please do help me in the thought process of how to remove the duplicate characters. Thank you! (JavaScript beginner here)
function get_common_characters(str1, str2) {
let common_chars = []
// YOUR CODE GOES HERE
new_str1 = str1.replace(" ", "").toLowerCase()
// console.log(new_str1)
new_str2 = str2.replace(" ", "").toLowerCase()
for (let i=0; i < new_str1.length; i++){
for (let j=0; j < new_str2.length; j++){
if (new_str1[i] == new_str2[i]){
common_chars.push(new_str1[i])
}
}
}
return common_chars
}
The below image is the output of the test cases in the console.
These are the test cases for the above codes.
While you could deduplicate the common_chars afterwards
return [...new Set(common_chars)]
I think a nicer looking (and less computationally complex) approach would be to make Sets of both strings ahead of time, then iterate through one of them while checking to see if the other contains the character in question.
function get_common_characters(str1, str2) {
const set1 = new Set(str1);
return [...new Set(str2)]
.filter(char => set1.has(char));
}
function get_common_characters(str1, str2) {
const set1 = new Set(str1.split(''))
const set2 = new Set(str2.split(''))
const result = []
for(let char of set1.values()){
if(set2.has(char)) result.push(char)
}
return result
}