Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  126] [ 6]  / answers: 1 / hits: 29790  / 7 Years ago, tue, december 19, 2017, 12:00:00

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

More From » arrays

 Answers
60

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>




[#55642] Friday, December 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jack

Total Points: 557
Total Questions: 96
Total Answers: 80

Location: Saint Helena
Member since Mon, Jan 16, 2023
1 Year ago
;