Reputation: 37
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
)
)
)}
Upvotes: 0
Views: 1240
Reputation: 15540
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
})
}
Upvotes: 3
Reputation: 806
use a filter
instead of map
for bedsAssign:
{tenants.map((row) =>
bedsAssign.filter(
(u) =>
row.id !== u.tenant_id && (
<MenuItem key={row.id} value={row.id}>
{row.fullName}
</MenuItem>
)
)
)}
the filter is going to only fill in the items that are meeting the condition you want.
EDIT: I noticed that you want to break once condition is met, this would work in this case:
{tenants.map((row) =>
for(let i of bedsAssign){
if(row.id !== i.tenant_id && (
<MenuItem key={row.id} value={row.id}>
{row.fullName}
</MenuItem>
)){
break
}
}
)
)}
Upvotes: -1
Reputation: 105
You can not break any array methods like forEach, filter, map etc. If you encounter a scenario where you want your loop to break then you should use traditional for loop.
Upvotes: 0