vsasv
vsasv

Reputation: 870

Combine a Reduce and Map Data Structure in Javascript?

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!

Upvotes: 1

Views: 572

Answers (1)

Bergi
Bergi

Reputation: 664579

You seem to be looking for

values.reduce((acc, el, i) => FOO_MAP.get(el.field)(acc, el, i), 0);

Upvotes: 3

Related Questions