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

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

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 Denunciar

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