Reduce the array to one row

I would like to use a function reduceinstead:

var result = '';
authors.forEach(
    function(author) {
        result += author.name + ', ';
    }
);
console.log(result);

So, authorsthere are several names in the array . Now I want to build a string with these names, separated by a comma (except for the last).

var result = authors.reduce(function (author, index) {
    return author + ' ';
}, '');
console.log(result);
+4
source share
5 answers

The noise of answers has just come, and here is another one!

The first option is the built-in js join method, which eliminates the need for reduction. 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 the array contains objects, you can 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);

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

- , , , name:

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

, . , :

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

join()

var authors = ["a","b","c"];
var str = authors.join(", ");
console.log(str);
Hide result

, if 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);
Hide result

, ...

var authors = [{
  name: "a"
}, {
  name: "b"
}, {
  name: "c"
}];

var res = authors.map( function(val) { return val.name; }).join(", ");
console.log(res);
Hide result

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);
Hide result
+1

:

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

console.log(result)
Hide result
0

. , s, , .

:

authors.reduce((prev, curr) => [...prev, curr.name], []).join(', ');
0

All Articles