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

464
Vistas
How to compare two arrays in javascript and remove the similar values?

I'm new to javascript and web development.

I am planning to compare two Strings and remove the same elements from the said strings.

for example:

str1 = "john" str2 = "jane"

str1 and str2 both have "j" and "n", and therefore removed from the string it's supposed to look like this: str1Res = "oh" str2Res = "ae"

this is my code. the problem is: the firstName variable is correctly processed. However, the secondName doesn't remove anything.

    var firstName = "john"
    var secondName = "jane"
    firstName = firstName.toLowerCase();
    secondName = secondName.toLowerCase();

    //remove whitespaces and split to array
    var firstNameArray = firstName.replaceAll(" ", "").split('');
    var secondNameArray = secondName.replaceAll(" ", "").split('');

    var firstNameRes = [];
    var secondNameRes = [];

    //duplicate array
    firstNameRes = firstNameArray;
    secondNameRes = secondNameArray;

  

    let i, j
   
    //loop the first name
    for (i = 0; i < firstNameArray.length; i++) {
      
      for (j = 0; j < secondNameArray.length; j++) {
        //pair characters of first name with characters from second name
        if (firstNameArray[i] == secondNameArray[j]) {
          //remove the element from the result array
          firstNameRes.splice(i, 1);
        }
      }
    }
    
    //loop the second name
    for (i = 0; i < secondNameArray.length; i++) {
      //pair characters of second name with characters from first name
      for (j = 0; j <firstNameArray.length; j++) {
        //remove the element from the result array
        if (secondNameArray[i] == firstNameArray[j]){
          secondNameRes.splice(i, 1);
        }
      }
    }

output: firstName: 'o','h' secondName: 'j','a','n', 'e' thanks in advance!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use regex to do that:

    var firstName = "john"
    var secondName = "jane"
    
    var reg1 = new RegExp("["+firstName+"]","g")
    var reg2 = new RegExp("["+secondName+"]","g")
    console.log(firstName.replace(reg2,""))    
    console.log(secondName.replace(reg1,""))

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is probably too advanced, but you can do this using regular expressions, like this:

var name1 = ...;
var name2 = ...;

var rx = new RegExp('[' + name2 + ']',"g");

name1 = name1.replace(rx,"");

Within regex, the brackets ('[' and ']') turn the string into a collection of characters to match

about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem in your code was you making the duplicated arrays that incorrectly, you need to copy arrays like that:

var firstName = "john"
    var secondName = "jane"
    firstName = firstName.toLowerCase();
    secondName = secondName.toLowerCase();

    //remove whitespaces and split to array
    var firstNameArray = firstName.replaceAll(" ", "").split('');
    var secondNameArray = secondName.replaceAll(" ", "").split('');

var firstNameRes = [...firstNameArray]; // Here the way we copy the ARRAY elements, it doesn't work like strings.
  var secondNameRes = [...secondNameArray];
  
  // I CHANGED ALL CODE BELOW FOR YOU TO WORK
  let indexToRemoveFirstName = [];
  let indexToRemoveSecondName = [];
    //loop to get indexes
    for (let i = 0; i < firstNameArray.length; i++) {
      
      for (let j = 0; j < secondNameArray.length; j++) {
        //pair characters of first name with characters from second name
        if (firstNameArray[i] == secondNameArray[j]) {
          //storing the indexes to remove from originals arrays
          indexToRemoveFirstName.push(i);
          indexToRemoveSecondName.push(j);
        }
      }
    }
    
    //loops to remove from Array after having the indexes, it needs to loop backwards:
    for (let i = indexToRemoveFirstName.length-1; i >= 0; i--){
    firstNameArray.splice(indexToRemoveFirstName[i], 1)
    }
    
    for (let y = indexToRemoveSecondName.length-1; y >= 0;y--){
    secondNameArray.splice(indexToRemoveSecondName[y], 1)
  }
      
      console.log(firstNameArray);
      console.log(secondNameArray);

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