1

I am trying to use the reduce pattern on a Javascript Array of objects. But, instead of doing this in a single reducer, I want to be able to use a different reducer based on a condition set for each of the items in the array. So, it would look like the following.

const FOO_MAP = new Map([
  ["Foo1", Bar1],
  ["Foo2", Bar2]]
);

function calcTotal(values) {
  if(values == null) return 0;
  return values.reduce(FOO_MAP.get(value.field));
}

function Bar1(previous, curr){...}
function Bar2(previous, curr){...}

Is this possible? Thanks!

svsav
  • 828
  • 3
  • 12
  • 29
  • Can you give a complete example with a `values` sample and `Bar` implementations, please? – Bergi Apr 09 '19 at 21:37

1 Answers1

3

You seem to be looking for

values.reduce((acc, el, i) => FOO_MAP.get(el.field)(acc, el, i), 0);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375