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

107
Vistas
How to get unique element from two arrays in js?

I'm trying to get unique (by id) values from two arrays.

But it returns whole array instead of { id: 3 }

const a = [{ id: 1 }, { id: 2 }];
const b = [{ id: 1 }, { id: 2 }, { id: 3 }];
    
const array3 = b.filter((obj) => a.indexOf(obj) == -1);
    
console.log(array3);

What's wrong here?

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

0

You cannot compare objects you should check that an element with that id doesn't exists in the other array

here I used some that returns a boolean if he can find a match

const a = [{
  id: 1
}, {
  id: 2
}];
const b = [{
  id: 1
}, {
  id: 2
}, {
  id: 3
}];

const array3 = b.filter(obj => !a.some(({id}) => obj.id === id));

console.log(array3)

about 4 years ago · Juan Pablo Isaza Denunciar

0

In your case, the following code gives all unique objects as an array, based on the id.

const a = [{
  id: 1
}, {
  id: 2
}];
const b = [{
  id: 1
}, {
  id: 2
}, {
  id: 3
}];

const array3 = b.filter(objB => a.some((objA) => objB.id !== objA.id));

console.log(array3)
about 4 years ago · Juan Pablo Isaza Denunciar

0

A different approach with a symmetrically result.

const
    take = m => d => o => m.set(o.id, (m.get(o.id) || 0) + d),
    a = [{ id: 1 }, { id: 2 }],
    b = [{ id: 1 }, { id: 2 }, { id: 3 }],
    map = new Map(),
    add = take(map),
    result = [];
    
a.forEach(add(1));
b.forEach(add(-1));
map.forEach((v, id) => v && result.push({ id }));
    
console.log(result);

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