0

Hello I have an array like this

const persons = [{name: 'John'}, {name: 'Rick'}, {name: 'Amy'}]

I would like to separate it with comma and add "and" before the last element

John, Rick and Amy

I can do

persons.map(person => <span>{person.name}, </span>)

but that will generate

John, Rick, Amy, 

is there a more efficient (fancy) way of doing this instead of iterating the array and add "," before all elements except the last one?

handsome
  • 2,335
  • 7
  • 45
  • 73

1 Answers1

2

Let try with simple check with conditions following index of element:

const persons = [{name: 'John'}, {name: 'Rick'}, {name: 'Amy'}]
const formmatted = persons.map((p,i) => (p.name + (i === persons.length - 2 ? ' and ' : (i !== persons.length - 1 ? ', ' : '')))).join("");
console.log(formmatted);
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18