Search code examples
javascriptreactjsarray-map

How to break a loop inside inline if in next js


I would like to stop the loop inside bedsAssign.map if row.id is not equal to u.tenant_id but putting break; doesn't work.

{tenants.map((row) =>
                 bedsAssign.map(
                   (u) =>
                     row.id !== u.tenant_id && (
                       <MenuItem key={row.id} value={row.id}>
                         {row.fullName}
                       </MenuItem>
                        break; --> not working
                     )
                 )
               )}

Solution

  • You can add filter before map to remove all bedsAssign items which are not matched with current row.id

    {
      tenants.map((row) =>
        bedsAssign
          .filter((u) => row.id !== u.tenant_id)
          .map((u) => (
            <MenuItem key={row.id} value={row.id}>
              {row.fullName}
            </MenuItem>
          ))
      )
    }
    

    If you want to break the loop, you can try to use some or find with a proper return for map

    {
      tenants.map((row) => {
        const isAssigned = bedsAssign.some((u) => row.id !== u.tenant_id)
            return isAssigned ? (<MenuItem key={row.id} value={row.id}>
              {row.fullName}
            </MenuItem>) : null    
      })
    }