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

462
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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