user3142695 user3142695 - 1 year ago 71
Javascript Question

Reduce array to a single string

I would like to use the

function instead of doing this:

var result = '';
function(author) {
result += + ', ';

So in the array
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 + ' ';
}, '');

Answer Source

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.

var authors = ['some author', 'another author', 'last author'];
var authorString = authors.join(",");

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 ={

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.

var authorString = authors.reduce(function(prevVal,currVal,idx){
    return idx == 0 ? currVal : prevVal + ', ' + currVal;
}, '')

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 ? : prevVal + ', ' +;
}, '')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download