user3142695 user3142695 - 4 months ago 10
Javascript Question

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

Answer

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);
Comments