Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map over properties in array and concat a string in JavaScript es6

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"

like image 874
svnm Avatar asked Jul 21 '16 06:07

svnm


People also ask

Can you map over a string in JavaScript?

Let's Map() Over a String()Turn the target string into an array, map() over it as per usual, and turn it back into a string: String. prototype. map = function(func) { let stringArray = this.

How do I combine array elements into strings?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Can we use map on array?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

How do I map an array in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


3 Answers

Use Array#Join :

authors.map((a) => `${a.name} is cool`).join(' ');

DEMO


NOTE : join is not related to ES6 , it is old .

like image 100
Abdennour TOUMI Avatar answered Oct 29 '22 21:10

Abdennour TOUMI


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`, '');
like image 31
Dayan Moreno Leon Avatar answered Oct 29 '22 23:10

Dayan Moreno Leon


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 `, ""))
like image 21
james emanon Avatar answered Oct 29 '22 23:10

james emanon