πΊπΈ Write a function commonCharacters(string1, string2)
which takes two strings as arguments and returns a string
containing the characters found in both strings
(without duplication), in the order that they appeared in string1
.
string
. Remember to skip spaces and characters you have already encountered!π¦π· Escribe la funciΓ³n commonCharacters(string1, string2)
que recibe dos strings como argumentos y devuelve un string
que contiene los caracteres existentes en ambos strings
(sin repeticion), en el orden que aparecen en string1
.
string
. Recuerda eliminar los espacion y los caracteres que ya fueron encontrados!π°π· λ κ°μ λ¬Έμμ΄μ μΈμλ‘ λ°κ³ λ λ¬Έμμ΄(μ€λ³΅ λ¬Έμ μμ΄)μμ μ‘΄μ¬νλ λ¬Έμλ€μ ν©ν λ¬Έμμ΄
λ°ννλ ν¨μλ₯Ό μμ±νμΈμ (commonCharacters(string1, string2)
). λ°νκ°μ λ¬Έμμ΄1
μ λνλ μμλλ‘ λμ€κ² νμμμ€.
string
μ λ°νν΄μΌ νλ€. λμ΄μ°κΈ°λ₯Ό μ κ±°νλ κ²κ³Ό μ΄λ―Έ μ°Ύμ λ¬Έμλ€μ μλ΅ν΄μΌ νλ κ²μ κΈ°μ΅νμμμ€!Example:
// Test
var commonCharacters = function('acexivou', 'aegihobu');
console.log(commonCharacters);
// return -> 'aeiou'
var commonCharacters = function(string1, string2) {
// Your CODE
};
// Test
commonCharacters("acexivou", "aegihobu"); // output> "aeiou"
commonCharacters("aeiou", "aaeeiioouu"); // output> "aeiou"
commonCharacters("i am a string", "i am also a string"); // output> "i am strng"
commonCharacters("vicapow", "wopaciv"); // output> "vicapow"
Click for the solution π
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
SOLUTION
var commonCharacters = function(string1, string2) {
// TODO: Your code here!
// new result array []
let temp = [];
let result = "";
if (string1 === string2) {
result = string1;
} else if (string1.length === 0 || string2.length === 0) {
result = "";
} else {
// two for loops
for (let i = 0; i < string1.length; i++) {
for (let j = 0; j < string2.length; j++) {
// if statement ? string1 char is equal to string2 char
// && is not inside result array
// TRUE> push to result array
if (string1[i] === string2[j] && !temp.includes(string2[j])) {
temp.push(string2[j]);
}
}
}
// Convert temp array into String
result = temp.join("");
}
return result;
};