menu

Questions & Answers

How to filter a nested array in React Typescript?

So I have this filter already working that implements a List in React (using mantine.dev as my css template)

<List>
  {locations.filter(location => {
    const locServices: Service[] = [];
    location.services.forEach(service => {
      if (service.locationPerformsService) {
        locServices.push(service);
      }
    });
    return query === ''
      ? location
      : location.name.toLowerCase().includes(query.toLowerCase()) && location;
  }).map((location, index) => (

    <UnstyledButton
      key={index}
      className={
        selectedLocation.risCode === location.risCode
          ? 'selected-location-navbar-item location-navbar-item'
          : 'location-navbar-item'
      }
    >

    </UnstyledButton>
  ))}
</List>

I do have the nested array I need to verify, but I can't see a better way to implement both together:

  locations.forEach(location => {
    const locServices: Service[] = [];
    location.services.forEach(service => {
      if (service.locationPerformsService) {
        console.log(locServices);
        locServices.push(service);
      }
    });
    if (locServices.length > 0) {
      console.log(location.name);
      console.log(locServices);
    }
  });

Can you guys give me a hint or show me how to continue ?

Cheers and thanks!

Answers(1) :

Can we use filter istead of for each ?


locations.forEach(location => {
    const locServices = location.services.filter(service => service.locationPerformsService);
    if (locServices.length > 0) {
      console.log(location.name);
      console.log(locServices);
    }
  });