'How can I remove the last comma from a map?
I have,
{
mydata.map(({
name
}) => ( <p style = {{
display: "inline" }} > { " " } { name }, </p>))
}
How can I remove the last comma in banana, apple, orange,
the result of the code, that is, the one after orange
and make it look something like this: banana, apple, orange
?
Thank you very much!
Solution 1:[1]
{mydata.map(({name}, idex) => (
<p style={{display:"inline"}}>
{" "}{name} {index === mydata.length - 1 ? "" : ","}
</p>
))}
Solution 2:[2]
Try this:
{
mydata.map(({name}, i) => (
<p style={{display:"inline"}}>
{i + 1 !== mydata.length? `{name}, ` : name}
</p>
)
)
}
Solution 3:[3]
Why are you using multiple p tags? I think, below code should do what you want to do.
<p style={{display:"inline"}}>
{mydata.map(item => item.name).join(', ')}
</p>
Solution 4:[4]
As a matter of fact, you can do that with simple CSS:
{mydata.map(({name}) => (<span className='item'>{" "}{name}</span>))}
CSS:
.item:not(:last-child)::after { content: ',' }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | alisasani |
Solution 2 | |
Solution 3 | Prime |
Solution 4 |