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"
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.
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.
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.
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.
Use 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 `, ""))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With