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(' ');

DEMO


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 `, ""))
Share:
16,347
svnm
Author by

svnm

javascript, ruby, css

Updated on August 09, 2022

Comments

  • svnm
    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
    Abdennour TOUMI almost 8 years
    @steveniseki : i update answer, i make code more elegant (brief)
  • demux
    demux almost 8 years
    Why would you use reduce rather than join for this?
  • Abdennour TOUMI
    Abdennour TOUMI almost 8 years
    map->join is the most performance . Check : jsfiddle.net/abdennour/2btx0c28/4
  • svnm
    svnm almost 8 years
    thanks another good option, more of a functional approach and works well
  • james emanon
    james emanon almost 8 years
    I 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
    thefourtheye almost 8 years
    This will leave a space at the beginning.
  • a better oliver
    a better oliver almost 8 years
    "i make code more elegant (brief)" (a) => can be a => for that matter
  • a better oliver
    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
    Abdennour TOUMI over 5 years
    Yep @abetteroliver, it matters because it does not comply with eslint rules; Check out aribnb JS coding conventions.
  • a better oliver
    a better oliver over 5 years
    I am confused. If you want your code to comply then why don't you change it?