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

129
Vistas
Removing elements that appear in one array from another array

I have an array of available items:

const items = [{id: 1, title: Item 1}, {id: 2, title: Item 2}, {id: 3, title: Item 3}]

and an array of items that my user has purchased:

const purchasedItems = [{id: 1, title: Item 1}, {id: 2, title: Item 2}]

I want to display an array of items that are still available to them to purchase that they haven't bought yet, i.e. just item 3 in this case. So I want an array returned with just Item 3 in it.

I have tried:

const availableItems = items.filter(
    (item) => !purchasedItems.includes(item)
  )

However this just returns a list of all the items again.

Think I must be missing something quite obvious, any help appreciated!

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

0

includes won't work here because it will only compare the items with a strict equality (as in item1 === item2). It will only works if your items are the same objects with the same reference.

A little example:

const obj1 = { test: 1 };
const obj2 = obj1;
const obj3 = { test: 1 };

console.log(obj1 === obj2); // true
console.log(obj1 === obj3); // false

So, in your case, you have to do a more complex work in your filter function:

const availableItems = items.filter(item1 => !purchasedItems.some(item2 => item1.id === item2.id));
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use findIndex() instead of includes

const items = [{ id: 1, title: 'Item 1' }, { id: 2, title: 'Item 2' }, { id: 3, title: 'Item 3' }]

const purchasedItems = [{ id: 1, title: 'Item 1' }, { id: 2, title: 'Item 2' }]

const availableItems = items.filter((item) => (purchasedItems.findIndex(purchasedItem => purchasedItem.id === item.id) == -1))

console.log(availableItems)

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