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

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);


Solution 1:[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:[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:[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:[4]

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>

Solution 5:[5]

just do it like this:

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

Solution 6:[6]

try array.toString()

you will get INV, INV, INV, INV

Solution 7:[7]

I know this is late, but this is BY FAR the easiest way without any functions. Works great in inline statements and requires no separate functions or mapping if that's what's needed in your case.

const items = [1, 2, 3, 4, 5];

console.log("Items: " + "" + items + ".")

The ""+ before the array adds the comma for some reason I don't fully understand why.

Solution 8:[8]

var List = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.data.map(function(item) {
          return <div>{item.join(",")}</div>;
        })}
      </div>
    );
  }
});

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

React.render(<List data={data} />, document.body);

Solution 9:[9]

var List = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.data.map(function(item) {
          return <div>{item.join(",")}</div>;
        })}
      </div>
    );
  }
});

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

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

enter code here


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
Solution 2
Solution 3 Mayank Shukla
Solution 4 vicky patel
Solution 5 toxxiczny
Solution 6 Di_Nerd
Solution 7 twominds
Solution 8
Solution 9 Bahrom