admin管理员组文章数量:1136458
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);
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);
Share
Improve this question
asked Jul 8, 2016 at 15:13
user3142695user3142695
17.3k55 gold badges194 silver badges372 bronze badges
1
- If you want to use reduce or a loop for some reason, you have to add a check to see if the current loop element is the last one or not. But just use join, it's one line of code to get what you want. – Shilly Commented Jul 8, 2016 at 15:15
7 Answers
Reset to default 163A 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);
Right, so it's an object. Let's map the names first then:
var result = authors.map(function( author ) {
return author.name;
}).join(', ');
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);
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(', ');
Try this:
var authors = ["Mikel", "Brad", "Jessy", "Pof", "MArting"]
var result = authors.reduce( (prev, curr) => prev +', '+ curr )
console.log(result)
I will add my 2 cents, two options here, either through map or using ternary operator:
const authors = [{name: 'John'}, {name: 'Jack'}, {name: 'Charles'}];
// Map
const reducedMap = authors.map(a => a.name).reduce((result, name) => `${result},${name}`);
// Ternary operator and initial value
const reducedTernary = authors.reduce((result, author) => `${result}${result ? ',' : ''}${author.name}` , '');
// Result :
// John,Jack,Charles
Here is a "Python Like" method to build a string in one line using an array or an Object.
// From an Array
['Hey', 'Hi', 'Hello!'].reduce((result, item, index) => (index !==0 ? `${result}, `: '')+`${item}`, '')
// From an Object
Object.entries({one: 1, two: 2, three: 3}).reduce((result, [key, value], index) => (index !==0 ? `${result}, `: '')+`${key} -> ${value}`, '')
I hope this helps. Cheers.
本文标签: javascriptReduce array to a single stringStack Overflow
版权声明:本文标题:javascript - Reduce array to a single string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736853361a1955605.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论