Search code examples
reactjsfilteruse-effectuse-state

comparing name property on objects in two separate arrays and creating a new filtered array in React


in my react component I have an array called providerServices and an array called userServices. Both hold multiple objects with a name property. on page load I need a filtered version of providerServices that does not include any objects with the same name property as the objects in userServices.

  useEffect(() => {
    userServices.map((us) => {
      setFilteredServices(providerServices.filter((service) => service.name !== us.name))
    })
  }, [])

my code above is only removing the first obj that matches instead of all that match. Some help or guidance would be much appreciated


Solution

  • You just need to filter out from providerServices every element that .find locates on userServices

    providerServices.filter(function(providerServicesObj) {
      return !userServices.find(function(userServicesObj) {
        return providerServicesObj.name === userServicesObj.name
      })
    })