Jason Brill Jason Brill - 1 month ago 8
Javascript Question

Multiple conditions to generate a string within a Map function

I am storing an array that looks like:

let arr = [
{
name: "James",
age: 24
},
name: "Patrick",
age: 20
},
{
name: "John",
age: 23
}
];


I am trying to get a string that will look like:

Hi James, Patrick and John
^ ^
| |
Comma And


Adding a
,
(comma) after each name but not after the one before the last. and the word
And
right before the last word. I'm using Map:

arr.map((l,i) =>
<span key={i}>
{i < arr.length - 1 ? `${l.name}, ` :
i === arr.length - 1 ? `and ${l.name}.` : ''}
</span>)


I get:

James, Patrick, and John
^
|
This is Extra


Is there a beautiful and easy way to get such result? and a function that will be pure and work on all number of names within the array? Preferably with ES6.. Thanks!

Answer

I think you're looking for

const names = arr.map((l,i) => html`<span key="${i}">${l.name}</span`);
const last = names.pop();
return names.length ? names.join(", ") + " and  " + last : last;

Don't use map for the parts that aren't the same for all items.