I have the following array of objects for example some authors and I want to map through them and return a string which has been concatenated with some formatting. I am for some reason having an issue with this fairly easy thing.
const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
let names = authors.map( (a, i) => {
return `${a.name} is cool`
})
console.log(names)
// ["Steven is cool","Nick is cool"]
// but I really want the string "Steven is cool Nick is cool"
How can I instead get this to map through and format it to a string?
e.g. "Steven is cool Nick is cool"
I have the following array of objects for example some authors and I want to map through them and return a string which has been concatenated with some formatting. I am for some reason having an issue with this fairly easy thing.
const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
let names = authors.map( (a, i) => {
return `${a.name} is cool`
})
console.log(names)
// ["Steven is cool","Nick is cool"]
// but I really want the string "Steven is cool Nick is cool"
How can I instead get this to map through and format it to a string?
e.g. "Steven is cool Nick is cool"
3 Answers
Reset to default 30Use Array#Join
:
authors.map((a) => `${a.name} is cool`).join(' ');
DEMO
NOTE : join
is not related to ES6 , it is old .
i for one prefer the use of reduce
ES5 version
autors.reduce(function (str, person) {
return (str+' '+person.name+ ' is cool');
}, '');
ES6 version
autors.reduce((str, person) => `${str} ${person.name} is cool`, '');
Here is another version so you don't have to map --> join.. you can just reduce.
const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
console.log(authors.reduce( (p,c) => `${p} ${c.name} is cool `, ""))
names.join(" ")
? – Bergi Commented Jul 21, 2016 at 6:45