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!
You can use reduce()
to do this
let arr = [{ name: "James", age: 24 }, { name: "Patrick", age: 20 }, { name: "John", age: 23 }]; var result = arr.reduce(function(r, e, i) { if ((i + 1) == (arr.length - 1)) { r += e.name; } else if ((i + 1) != arr.length) { r += e.name + ', '; } else { r += ' and ' + e.name; } return r; }, 'Hi '); console.log(result)
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.
You can do this.
arr.map((l,i) =>
if (i <arr.length-1) {
if(i === arr.length-2) {
<span key={i}>
{`${l.name} `}
</span>)
} else {
<span key={i}>
{`${l.name}, `}
</span>)
}
} else {
<span key={i}>
`and ${l.name}.`
</span>)
}
you can try with below code
arr.map((l,i) =>
<span key={i}>
{i < arr.length - 1 && i !== arr.length - 2 ? `${l.name}, ` : ''}
{i === arr.length - 2 ? `${l.name} ` : ''}
{i === arr.length - 1 ? `and ${l.name}.` : ''}
</span>)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.