You can know which call to map
's callback is the last by using the index argument you get passed:
{cars.map((car, index) => {
return(
<p key={car.id}>{car.title} {index < cars.length - 1 ? ", " : ""}</p>
);
})}
But note that p
is usually a block element, so the cars would be stacked rather than shown inline with spaces (and commas) between them. I'd use span
instead (although you can mark the p
as inline
if you want). I've used span
below.
You can also use a concise arrow function rather than a verbose one with a function body:
{cars.map((car, index) =>
<span key={car.id}>{car.title} {index < cars.length - 1 ? ", " : ""}</span>
)}
Live example:
const cars = [
{id: 1, title: "Ford"},
{id: 2, title: "Toyota"},
{id: 3, title: "Lexus"},
];
ReactDOM.render(
<div>{cars.map((car, index) =>
<span key={car.id}>{car.title}{index < cars.length - 1 ? ", " : ""}</span>)
}</div>,
document.getElementById("root")
);
<div id="root"></div>
<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>
In a comment somewhere you asked how to make the space non-breaking (though I think that may have been because you were using inline-block
with a p
element, and so normal spaces weren't being rendered). To do that, just replace ", "
with ",\u00A0"
above.
const cars = [
{id: 1, title: "Ford"},
{id: 2, title: "Toyota"},
{id: 3, title: "Lexus"},
];
ReactDOM.render(
<div>{cars.map((car, index) =>
<span key={car.id}>{car.title}{index < cars.length - 1 ? ",\u00A0" : ""}</span>)
}</div>,
document.getElementById("root")
);
<div id="root"></div>
<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>