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 reduce() is an inbuilt array method that executes a callback function known as a reducer on each element of the array and results in a single output value. The reduce() method executes the function for each value of the array (non-empty array) from left to right.
We use reduce() when we need to analyze all of the elements in an array and return just a single value, it can transform the data from the array into a number, string, or an object. The reducer function is always taking from the two elements (the accumulator and the current value) reducing them into one value.
JavaScript Array reduce()The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With