Reputation: 33
I'm learning how to utilize reduce but still have a little bit of a mental block on the acc, val parameters. My goal is to be able to pass additional parameters into a reducer function and feel pretty certain that I am just going about it the wrong way.
const array = [1,2,3,4,5];
const multiply = (num, multiplier) => num * multiplier;
const multiplier = (acc, val) => acc += multiply(val, 4);
const result = array.reduce(multiplier);
console.log(result);
In this code block, I'm running the multiplier reducer against my array to multiple each value by 4. This code works correctly and is all well and good, but I want to make it so that any value can be passed in instead of the hard coded 4. I've tried things like
const multiplier = (acc, val, multiple) => acc += multiply(val, multiple);
const result = array.reduce(multiplier(4)
to be able to pass in a multiplier but the "acc, val" params are messing me up because I don't specifically "see" what the values are that are passed in. I know that it passes in 1 then 2 then 3 etc. but how do you pass an additional parameter in such as a custom multiplier instead of needing a different multiplier function for every multiple?
Upvotes: 3
Views: 530
Reputation: 10382
do it as a currying function that will work as expected:
const multiplier = factor => (acc, val) => acc += multiply(val, factor);
const result = array.reduce(multiplier(4));
This way when you call multiplier(4)
it will return a function tailored with the desired factor
that you can use at your reducer like you intended to.
Upvotes: 1