Willem de Wit Willem de Wit - 1 year ago 77
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?

Answer Source

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;
}, []);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download