How to add a comma in array.map after every element except last element in React JSX

21,597

Solution 1

As commented you can use:

array.map((item, index) => ({ (index ? ', ': '') + item }))

Also, since you want to display text inline, using a div is not appropriate. Instead you can/should use an inline element like span

var List = React.createClass({
  render: function() {
    return (
      <div>
        {
          this.props.data.map(function(item, index) {
            return <span key={`demo_snap_${index}`}>{ (index ? ', ' : '') + item }</span>;
          })
        }
      </div>
    );
  }
});

var data = ["red", "green", "blue"];

ReactDOM.render(<List data={data} />, demo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>

Solution 2

Use the CSS adjacent sibling combinator (+) to add pseudo element (::before) with a comma to all sibling items, but the 1st:

const List = ({ data }) => (
  <div>
    {data.map((item, idx) => (
      <span className="item" key={idx}>{item}</span>
    ))}
  </div>
);

var data = ["red", "green", "blue"];

ReactDOM.render(<List data={data} />, demo);
.item + .item::before {
  display: inline-block;
  white-space: pre;
  content: ", ";
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="demo"></div>

Another option is to create a generic component that expects a list of items, and an optional separator, and maps the children to include the separator. This uses the index method detailed in Rajesh's answer.

Note: due to the old BabelJS version used by the SO snippet, I need to use <Fragment> instead of the shorter <> for a fragment.

const { Children, Fragment } = React;

const AddSeparators = ({ children, separator = ', ' }) =>
  Children.map(children, (child, idx) => (
    <Fragment>
      {idx ? separator : ''}
      {child}
    </Fragment>
  ));

const List = ({ data }) => (
  <div>
    <AddSeparators separator=" | ">
      {data.map((item, idx) => (
        <span key={idx}>{item}</span>
      ))}
    </AddSeparators>
  </div>
);

var data = ["red", "green", "blue"];

ReactDOM.render(<List data={data} />, demo);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="demo"></div>

Solution 3

What you can do is, check the index of item, if index is not equals to the last item render the , otherwise nothing.

Write it like this:

{
    this.props.data.map((item, i, arr) => <span>{item} {i != (arr.length-1) ? ',' : ''}</span>)
}

You can also store the total data length in a separate variable and instead of checking the arr.length in each iteration check with that variable.

Working example:

var List = React.createClass({
  render: function() {
    return (
      <div>
        {
	   this.props.data.map((item, i, arr) => <span>{item} {i != (arr.length-1) ? ', ' : ''}</span>)
        }
      </div>
    );
  }
});

var data = ["red", "green", "blue"];

ReactDOM.render(<List data={data} />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Solution 4

just do it like this:

<div>{array.join(',')}</div>

Solution 5

const data = ["red", "green", "blue"];

class List extends React.Component{
render(){
return( 
<div>
{this.props.data.map((item, index) => {
  return <span>{ (index ? ', ' : '') + item }</span>;
})}
</div>
)
}
}

ReactDOM.render(
<List data={data}/>,
document.getElementById('demo')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>

Share:
21,597

Related videos on Youtube

Ajay G.
Author by

Ajay G.

I am a front-end engineer from India. I build applications for the web, mobile and server-side platforms. I write code, develop user interfaces and do pretty much anything if it intrigues me.

Updated on August 28, 2022

Comments

  • Ajay G.
    Ajay G. over 1 year

    How can I add a trailing comma after every element of an array for making a list like:

    INV, INV, INV, INV

    Note that the last element doesn't have a trailing comma

    Currently iterating the list with array.map:

    var List = React.createClass({
      render: function() {
        return (
          <div>
            {this.props.data.map(function(item) {
              return <div>{item}</div>;
            })}
          </div>
        );
      }
    });
    
    var data = ["red", "green", "blue"];
    
    React.render(<List data={data} />, document.body);
    
    • zabusa
      zabusa over 6 years
      you need a string in return?
    • Rajesh
      Rajesh over 6 years
      You can try a simple hack: array.map((item, index) => (<div>{ (index ? ', ': '') + item}</div>)). What this will do is, check if index is valid, add a comma else blank string. And since 0 in JS is falsey, it will skip for 1st entry
    • Mohit Bhardwaj
      Mohit Bhardwaj over 6 years
      arr.join(',');
    • Rajesh
      Rajesh over 6 years
      @MohitBhardwaj Join will make it string and not Array<ReachNode>
    • Shubham Khatri
      Shubham Khatri over 6 years
      Why do you need a trailing comma for
    • Mohit Bhardwaj
      Mohit Bhardwaj over 6 years
      @Rajesh you're right if we need an array.
    • Rajesh
      Rajesh over 6 years
      React render needs ReactNode or JSX. Not sure how it will interpret string. Also, since ReactNode is an object, it might return "[object Object], [object Object]..."
    • Ajay G.
      Ajay G. over 6 years
      @ShubhamKhatri Want to display an inline list of titles like: JavaScript, React, Angular. It should be a string.
    • vibhor1997a
      vibhor1997a over 6 years
      data=data.map((x,i,arr)=>(i<arr.length-1)?x+',':x)
    • Rajesh
      Rajesh over 6 years
      @AjayGupta In that case, your code is incorrect. Div is a block element. Instead use a span or wrap everything in 1 div. In this case you can use Mohit's suggestion to use join
    • Abhay Shiro
      Abhay Shiro over 4 years
      Dude just do .map and then .join.. example: array.map(c => c).join(',')
  • Rajesh
    Rajesh over 6 years
    Just an opinionated comment but I would prefer using JS instead. Also using a div and adding display: inline-block looks weird.
  • Ori Drori
    Ori Drori over 6 years
    Why would you prefer JS in this case?
  • Rajesh
    Rajesh over 6 years
    I prefer keeping UI changes to CSS and such manipulation to JS. Again, this is just my preference/opinion. Yes using CSS would be more performant, but it might reduce readability.
  • Ori Drori
    Ori Drori over 6 years
    I actually considers this a part of the design, thus fitting for CSS. Why would it reduce readability? I'm interested in knowing your opinion :)
  • Rajesh
    Rajesh over 6 years
    Why am I getting a feeling, this is one of those conversation where you say something incorrect and your friend instead of correcting you, would flow around and play with you for fun. :-p
  • Rajesh
    Rajesh over 6 years
    But to answer, in my opinion, what is to be rendered should belong to HTML + JS and how they should be shown belongs to CSS. But I agree, I have a lot to understand.
  • Ori Drori
    Ori Drori over 6 years
    @Rajesh - your feeling is incorrect in this case :) Pseudo elements and content are indeed a grey area. The question is - are the commas part of the content itself, or are they part of the design? And you can answer it both ways. I'm not sure about readability though. On one hand it might be confusing - "where is the comma coming from?". On the hand it reduces noise in the JSX, and a short inspect will show you where it comes form. So, as you stated - a matter of opinion.
  • Ori Drori
    Ori Drori over 6 years
  • James Love
    James Love about 6 years
    Remember to add a key={index} to the <span> or you'll get a warning in the console
  • SJ19
    SJ19 almost 4 years
    Just came across this and I wanted to say thanks for this solution! I'm also wondering why does index ? ',':'' work? :) I don't understand the logic behind it, as index is just a number?
  • Rajesh
    Rajesh almost 4 years
    @SJ19 Since we are prepending value, we have to make sure we dont add extra comma. So for that I do that ternary operator. Since in JS 0 is falsey, for first iteration, nothing will be added
  • SJ19
    SJ19 almost 4 years
    @Rajesh OH, I kept thinking the other way around, I was wondering how it knew we were on the last index. Now it makes sense. Thanks! Smart solution.
  • sudhee_bsp
    sudhee_bsp almost 3 years
    great! wanted such way.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.