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

Time:12-24

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

CodePudding user response:

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
  })
})

CodePudding user response:

This should work fine, one-liner solutions in ES6:

useEffect(() => {
    const filteredServices = providerServices.filter(({ name: providerServicesName }) => 
        !userServices.some(({ name: userServicesName }) => userServicesName === 
        providerServicesName));
    setFilteredServices(filteredServices);
  }, [])

  • Related