Search code examples
javascriptreactjse-commerce

How map throw forEach() inside the filter() in ReactJs


Here I have a problem mapping throw forEach() inside the filter(), I'm trying to filter products so for each product object I want to get to the product.categories array, and for each product category I want to check if the product category id === the page category id and then map throw them, and display the product that matches, but nothing gets displayed.

<div>
    {products.filter(filterProduct => filterProduct.categories.forEach(eachProductCategory => eachProductCategory.id === category.id)).map(product => (
                              <Product />
</div>


Solution

  • You could try .some instead of forEach

    <div>
      {products
        .filter((filterProduct) =>
          filterProduct.categories.some(
            (eachProductCategory) => eachProductCategory.id === category.id
          )
        )
        .map((product) => (
          <Product />
        ))}
    </div>
    

    forEach doesn't return anything that was the problem

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach