Search code examples
javascriptarraysreactjscomponents

Why does Javascript .filter() not return anything with an active filter (== or ===) but works fine if the boolean logic is of type != or !==?


import React from "react";
import productsData from "./products.js";
import Product from "./Product.js";

function App() {
  const arrrayOfImportedProducts = productsData.map((x) => (
    <Product
      id={x.id}
      name={x.name}
      price={x.price}
      description={x.description}
    />
  ));

  const array2 = arrrayOfImportedProducts.filter((y) => y.id != 1);

  return <div>{array2}</div>;
}

export default App;

When I run the code, everything works fine except for the .filter() method. It gives me a blank screen whenever I use == or === to filter a specific element. When I use !== or !=== it shows me all elements of array2 including the ones that shouldn't be in there. Why is it not working?


Solution

  • Since you're doing your mapping first and your filtering after, your filter function is checking the .id property of react elements. React elements don't have an id property. So since the id will never match, your code with !== will always pass, and thus everything is included. And the opposite if you use ===: it will never pass, and so nothing is included.

    You will need to switch the order of your code:

    function App() {
      const filteredProducts = arrrayOfImportedProducts.filter((y) => y.id != 1);
      const arrrayOfImportedProducts = filteredProducts.map((x) => (
        <Product
          id={x.id}
          name={x.name}
          price={x.price}
          description={x.description}
        />
      ));
    
      return <div>{arrrayOfImportedProducts}</div>;
    }