Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How do write a function that takes in 2 strings and return an array of common characters (should not contain any duplicates)?

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.

enter image description here

These are the test cases for the above codes.

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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));
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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
 }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda