最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I remove the last comma from a map? - Stack Overflow

programmeradmin3浏览0评论

I have,

{
  mydata.map(({
    name
  }) => ( <p style = {{
        display: "inline" }} > { " " } { name }, </p>))
}

How can I remove the last ma 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!

I have,

{
  mydata.map(({
    name
  }) => ( <p style = {{
        display: "inline" }} > { " " } { name }, </p>))
}

How can I remove the last ma 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!

Share Improve this question edited Mar 29, 2021 at 12:10 Not A Robot 2,6942 gold badges19 silver badges37 bronze badges asked Mar 29, 2021 at 10:00 TomTom 1831 gold badge3 silver badges14 bronze badges 2
  • Maybe using the index from the map callback index === mydata.length - 1 ? '' : ','? – evolutionxbox Commented Mar 29, 2021 at 10:01
  • 1 Maybe better to use Array.join(', ');? – tarkh Commented Mar 29, 2021 at 10:03
Add a ment  | 

4 Answers 4

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

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>

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

Try this:

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

评论列表(0)

  1. 暂无评论