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!

1
  • Can you give a complete example with a values sample and Bar implementations, please? Commented Apr 9, 2019 at 21:37

1 Answer 1

3

You seem to be looking for

values.reduce((acc, el, i) => FOO_MAP.get(el.field)(acc, el, i), 0);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.