DEV Community

taiseen
taiseen

Posted on • Edited on

Display the same category products, but exclude the selected one

Building a website like e-commerce, inside it has lots of behavioral needs to fulfill & one of those is, to display all same category products but except that user already selected or opened at UI...

then this piece of logic is useful...

const allProducts = [
  { id: 1, category: "mobile", product: 'Sammung S20' },
  { id: 2, category: "cloth", product: 'T-Shirt' },
  { id: 3, category: "mobile", product: 'OnePlus 7T' },
  { id: 4, category: "cloth", product: 'Formal Pant' },
  { id: 5, category: "mobile", product: 'IPhone-14 Max Pro' },
]
Enter fullscreen mode Exit fullscreen mode
const selectedProduct = { category: "mobile", id: 5 };
Enter fullscreen mode Exit fullscreen mode
const result = allProducts
  .filter(item => item.category === selectedProduct.category)
  .filter(product => product.id !== selectedProduct.id);
Enter fullscreen mode Exit fullscreen mode
console.log(result);

/*
  { id: 1, category: "mobile", product: 'Samsung S20' },
  { id: 3, category: "mobile", product: 'OnePlus 7T' },
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)