Reduce array to a single string

Javascriptunderscore.js

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Right, so it's an object. Let's map the names first then:

var result = authors.map(function( author ) {
    return author.name;
}).join(', ');

Solution 3 - Javascript

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

Solution 4 - Javascript

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(', ');

Solution 5 - Javascript

Try this:

var authors = ["Mikel", "Brad", "Jessy", "Pof", "MArting"]
var result = authors.reduce( (prev, curr) => prev +', '+ curr )

console.log(result)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3142695View Question on Stackoverflow
Solution 1 - JavascriptabigwonderfulView Answer on Stackoverflow
Solution 2 - JavascriptShillyView Answer on Stackoverflow
Solution 3 - JavascriptepascarelloView Answer on Stackoverflow
Solution 4 - JavascriptRonjarkView Answer on Stackoverflow
Solution 5 - JavascriptelreedaView Answer on Stackoverflow