view raw
Willem de Wit Willem de Wit - 8 months ago 32
Javascript Question

Combining some array items

I'm kind of new to functional programming and I try to do the following: Let's say I have an array of values:

and I want that every item which ends with a
is merged with the following array entry:

Of course I can do this by making a for-loop:

var test = ['a', 'b-', 'c'], result = [];

for (var i=0;i<test.length;i++) {
var curr = test[i];
if (curr.endsWith('-')) {
curr += test[i+1];

But how can one do this without the for loop?


One possible approach (with .reduce):

var arr = ['a', 'b-', 'c'];
var trans = arr.reduce(function(acc, cur) {
  if (acc.length && acc[acc.length - 1].slice(-1) === '-') {
    acc[acc.length - 1] += cur;
  else {
  return acc;
}, []);