Reduce array to a single string
I would like to use the reduce
function instead of doing this:
var result = '';
authors.forEach(
function(author) {
result += author.name + ', ';
}
);
console.log(result);
So in the array authors
there are several names. Now I want to build a string with this names, separated by comma (except the last one).
var result = authors.reduce(function (author, index) {
return author + ' ';
}, '');
console.log(result);
A flurry of answers just came in and here is one more!
The first option is using the native js join method which eliminates the need for reduce. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
var authors = ['some author', 'another author', 'last author'];
var authorString = authors.join(",");
console.log(authorString);
IMPORTANT - if you're array contains objects, then you might want to map it before joining:
var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}]
var authorString = authors.map(function(author){
return author.name;
}).join(",");
console.log(authorString);
or, if you're really fired up about using reduce, just make sure you use the previous value, current value and index when passing in the callback. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var authorString = authors.reduce(function(prevVal,currVal,idx){
return idx == 0 ? currVal : prevVal + ', ' + currVal;
}, '')
console.log(authorString);
IMPORTANT - again if your array contains objects then you will want to make sure you are using the 'name property':
var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}];
var authorString = authors.reduce(function(prevVal,currVal,idx){
return idx == 0 ? currVal.name : prevVal + ', ' + currVal.name;
}, '')
console.log(authorString);
Right, so it's an object. Let's map the names first then:
var result = authors.map(function( author ) {
return author.name;
}).join(', ');
You are reinventing join()
var authors = ["a","b","c"];
var str = authors.join(", ");
console.log(str);
if you want to use reduce add an if check
var authors = ["a","b","c"];
var result = authors.reduce(function (author, val, index) {
var comma = author.length ? ", " : "";
return author + comma + val;
}, '');
console.log(result);
Since I missed the mapping part to make people happy...
var authors = [{
name: "a"
}, {
name: "b"
}, {
name: "c"
}];
var res = authors.map( function(val) { return val.name; }).join(", ");
console.log(res);
OR
var authors = [{
name: "a"
}, {
name: "b"
}, {
name: "c"
}];
var result = authors.reduce(function(author, val, index) {
var comma = author.length ? ", " : "";
return author + comma + val.name;
}, '');
console.log(result);
I came across this also. Most of these answers dont take into account that you want the authors name, meaning you have an array of objects.
A one line solution:
authors.reduce((prev, curr) => [...prev, curr.name], []).join(', ');