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

118
Vistas
Filter id in an array of object based on an array of id's

I am trying to display Heart icon for the items that are added to the Wishlist. I am using local storage to save the items that are wishlisted. I have an array of id's such as wishlistIds = [123,425,212,512,516]. So I want to check if the id's in that array matches with the array of objects (which are the products). Product array of objects looks like this;

 items = [{id:123, productName:"Cheese", price: 15.99}, {id:599, productName: "Honey", price:21.99}]

I have been trying to use Array.filter method to achieve what I want, but couldn't make it work;

wishlistIds.filter(w => w.id === items.id)

The above code returns me all the ids inside the wishlistIds without filtering the id's inside the the items. What is the correct way to approach this problem?

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

0

Create a Set of item IDs and use that to filter the wishlist array

const wishlistIds = [123,425,212,512,516]
const items = [{id:123, productName:"Cheese", price: 15.99}, {id:599, productName: "Honey", price:21.99}]

const itemIds = new Set(items.map(({ id }) => id))

const filteredWishlist = wishlistIds.filter(id => itemIds.has(id))

console.log(filteredWishlist)

I'm using a Set here as Set.prototype.has() is O(1) time complexity as opposed to Array.prototype.includes() which is O(n).

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#performance

about 4 years ago · Juan Pablo Isaza Denunciar

0

First filter the list, then map it to get just the ID

let wishlistIds = [123,425,212,512,516]
let items = [{id:123, productName:"Cheese", price: 15.99}, {id:599, productName: "Honey", price:21.99}]
let hearts = items.filter(w => wishlistIds.includes(w.id)).map(w => w.id)
console.log(hearts)

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