Willem de Wit Willem de Wit - 2 months ago 7
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:

['a','b-','c']
and I want that every item which ends with a
'-'
is merged with the following array entry:
['a','b-c']
.

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];
i++;
}
result.push(curr);
}


But how can one do this without the for loop?

Answer

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 {
    acc.push(cur);
  }
  return acc;
}, []);
Comments