Tom
Tom

Reputation: 183

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!

Upvotes: 4

Views: 2766

Answers (4)

crispengari
crispengari

Reputation: 9333

Try this:

{
 mydata.map(({name}, i) => (
          <p style={{display:"inline"}}>
            {i + 1 !== mydata.length? `{name}, ` : name} 
          </p>
     )
  )
}

Upvotes: 1

Sidorina
Sidorina

Reputation: 66

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: ',' }

Upvotes: 1

Prime
Prime

Reputation: 2849

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>

Upvotes: 3

alisasani
alisasani

Reputation: 2968

{mydata.map(({name}, idex) => (
                            <p style={{display:"inline"}}>
                                {" "}{name} {index === mydata.length - 1 ? "" : ","}
                            </p>
                            ))}

Upvotes: 5

Related Questions