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

127
Vistas
Merge Arrays With Only Elements in Both (Efficiently)

I have some working code, though it seems like it should be much more efficient. I feel there are too many filters working through the same data sets. Is there a cleaner or more efficient way of merging 2 arrays without duplicating?

const x = [1,3,7,4,9];
const y = [2,3,9,13,4];

const yFilteredByX = y.filter(element => x.includes(element));
const xFilteredByY = x.filter(element => y.includes(element));

const unique = (value, index, self) => {
    return self.indexOf(value) === index;
};

const newArr = yFilteredByX.concat(xFilteredByY);
const uniqueArr = newArr.filter(unique);

console.log(uniqueArr);

Currently outputs [3,9,4] successfully.

I made a quick fiddle

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

0

  • Create a Set for each array
  • Iterate over the items of the first using Array#filter and return only those in the second set

const _getCommonElements = (arr1 = [], arr2 = []) => {
  const set1 = new Set(arr1), set2 = new Set(arr2);
  return [...set1].filter(e => set2.has(e));
}

console.log( _getCommonElements([1,3,7,4,9], [2,3,9,13,4]) );

about 4 years ago · Juan Pablo Isaza Denunciar

0

Create a Set from one, and then filter the other by checking if the set has elements.

const x = [1, 3, 7, 4, 9];
const y = [2, 3, 9, 13, 4];

const uniqueInX = new Set(x);
const uniqueInBoth = y.filter(e => uniqueInX.has(e));

console.log(uniqueInBoth);

about 4 years ago · Juan Pablo Isaza Denunciar

0

It seems like you intend to calculate the intersection of two sets, thus the corresponding function operation from the mozilla developer docs can be used, e.g.

const x = [1, 3, 7, 4, 9];
const y = [2, 3, 9, 13, 4];

function intersection(setA, setB) {
  let _intersection = new Set()
  for (let elem of setB) {
    if (setA.has(elem)) {
      _intersection.add(elem)
    }
  }
  return _intersection
}

const setX = new Set(x);
const setY = new Set(y);

const commonSet = intersection(setX, setY);

console.log(...commonSet); // [3, 9, 4]

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