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' },
]
const selectedProduct = { category: "mobile", id: 5 };
const result = allProducts
.filter(item => item.category === selectedProduct.category)
.filter(product => product.id !== selectedProduct.id);
console.log(result);
/*
{ id: 1, category: "mobile", product: 'Samsung S20' },
{ id: 3, category: "mobile", product: 'OnePlus 7T' },
*/
Top comments (0)