map over properties in array and concat a string in JavaScript es6
16,347
Solution 1
Use Array#Join
:
authors.map((a) => `${a.name} is cool`).join(' ');
NOTE : join
is not related to ES6 , it is old .
Solution 2
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`, '');
Solution 3
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 `, ""))
Comments
-
svnm over 1 year
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"
-
Abdennour TOUMI almost 8 years@steveniseki : i update answer, i make code more elegant (brief)
-
demux almost 8 yearsWhy would you use
reduce
rather thanjoin
for this? -
Abdennour TOUMI almost 8 years
map->join
is the most performance . Check : jsfiddle.net/abdennour/2btx0c28/4 -
svnm almost 8 yearsthanks another good option, more of a functional approach and works well
-
james emanon almost 8 yearsI believe reduce will always more performant because it doesn't have to create a intermediary array. Also, in your fiddle, in chrome - reduce is more performant. But I tend to fluctuate between a reduce and a map/join solution. Depends on how I am feeling.
-
thefourtheye almost 8 yearsThis will leave a space at the beginning.
-
a better oliver almost 8 years"i make code more elegant (brief)"
(a) =>
can bea =>
for that matter -
a better oliver almost 8 years@AbdennourTOUMI If you want to test performance, then use a dedicated framework. Simple time measuring is pointless.
-
Abdennour TOUMI over 5 yearsYep @abetteroliver, it matters because it does not comply with eslint rules; Check out aribnb JS coding conventions.
-
a better oliver over 5 yearsI am confused. If you want your code to comply then why don't you change it?