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

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

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

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

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