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

98
Visualizações
Compare two arrays and push same element in one array and rest in other array in javascript

Compare two arrays and push same element in one array and rest in other array in javascript

const arr1 = ['a', 'c', 'e', 'j', 'p', 'r', 'l'];

const arr2 = ['e', 'r'];

**Expected response :**

Same elements ['e', 'r']
different elements ['a', 'c', 'j', 'l']

expected array : ['ac', 'e', 'jp', 'r', 'l']

I have tried this is it correct way ?

const res = [];
  let txt = '';

  for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (arr1[i] === arr2[j]) {
        res.push(txt);
        res.push(arr2[j]);
        j += 1;
        txt = '';
      } else if (j === arr2.length - 1) {
        txt += `${arr1[i]} `;
        if (i === arr1.length - 1) {
          res.push(txt);
        }
      }
    }
  }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

By observing your expected array and your own code segment I could guess what you are trying to achieve (It's not full clear from your problem statement). If my understanding is correct then your code might not result in expected answer in all cases if the input array is not fixed. I have modified your code as below. Have a check. set arr2 input as ['e', 'r', 't'] , or ['a', 'c', 'e', 'j', 'p', 'r', 'l'] and check the output. Let me know if it's helpful.

for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (arr1[i] === arr2[j]) {
        if(txt!=='') res.push(txt)
        res.push(arr2[j]);
        txt = '';
        break;
      } 
      else if (j === arr2.length - 1) {
        txt+= txt===''?`${arr1[i]}` : ` ${arr1[i]}`
        if (i === arr1.length - 1) {
          res.push(txt);
        }
      }
    }
 }
about 4 years ago · Juan Pablo Isaza Relatório

0

To group the elements by same and different you can just use filter.

const arr1 = ['a', 'c', 'e', 'j', 'p', 'r', 'l'];
const arr2 = ['e', 'r'];

const sameElements = [...arr1].filter(x => arr2.includes(x))
const differentElements = [...arr1].filter(x => !arr2.includes(x))

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