Skip to content
Advertisement

JavaScript – examples of reduce() function

I’m looking at this example of use of reduce() function.

function add(runningTotal, currentValue) {
   return runningTotal + currentValue;
}

var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add);
print(sum); // displays 55

Could you give show me some other examples of using reduce() – I’m not sure I fully follow how it works.

Thank you

Advertisement

Answer

What reduces does is take an initialValue, a function with 2 essential parameters (can take more) and a list of values. If no initialValue is provided then it’s assumed it’s the first element of the list. The function is supposed to do something with the previousValue usually used as an accumulator and the nextValue.

So, assume you have a list of values: [1, 2, 3, 4, 5] and the function is supposed to add the 2 parameters and an initialValue of 0.

First step:

0 + 1 = 1
    2
    3
    4
    5

Second step:

1 + 2 = 3
    3
    4
    5

Third Step:

3 + 3 = 6
    4
    5

Fourth Step:

6 + 4 = 10
    5

Fifth Step:

10 + 5 = 15 //Final value

As you can see, the input went from a list to a single value, hence the name reduce. In your example, there’s no initialValue (that’s the second argument), so it’s as if started on the second step.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement