Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use array.reduce to join strings with comma, but avoid the extra comma

I have an array of objects to be transformed and merged into a single string with array.reduce.

const arr = [{id: 7, task: "foo"}, {id: 22, task: "bar"}]

The result should be 7. foo, 22. bar

If I write this code, it will work but produce , 7. foo, 22.bar:

arr.reduce((pre,cur)=> pre + `, ${cur.id}. ${cur.task}`, '')

How can I properly do this without the extra comma, preferably only in FP?

like image 561
rasperry Avatar asked Oct 20 '25 02:10

rasperry


1 Answers

Is reduce a requirement? Map is easier to understand and read.

arr.map(o => `${o.id}. ${o.task}`).join(',')
like image 102
Andreas Dolk Avatar answered Oct 21 '25 16:10

Andreas Dolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!