Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda