0

How can I see in the map of products if that product is in the favorites?

Log of products 

[
{id: 1, product_name: “product one”},
{id: 2, product_name: “product two”},
{id: 3, product_name: “product three”}
]

Log of favorites

[
{id: 1, product_name: “product one”},
{id: 2, product_name: “product two”}
]

{products.map((item} => 
// Here, if the product is in the favorites list then show x else show y
// I need to check here if the product is in the favorites list, to show two different types of icons
)

I don’t know how to do, I also tried to map to favorites with product id = favorite product id, but it didn't work

1 Answer 1

2

var products = [{
    id: 1,
    product_name: 'product one'
  },
  {
    id: 2,
    product_name: 'product two'
  },
  {
    id: 3,
    product_name: 'product three'
  }
]
var favorites = [{
    id: 1,
    product_name: 'product one'
  },
  {
    id: 2,
    product_name: 'product two'
  }
]

const solution = products.map((product)=>{
  return favorites.find(el=>el.product_name === product.product_name) ? 'x' : 'y'
})

Sign up to request clarification or add additional context in comments.

1 Comment

.find technically returns the object from the list, not a boolean "exists". .some is strictly "does it exist". There are some strange edge cases where .find and .some could give a different result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.