JavaScript reduce()
condensing elements of an array into a single value
Motivation
Suppose we have an array and we wish to find the sum of all its values...
We could use the built-in reduce()
function to iterate and summarize:
So unlike map()
and filter()
, the callback function passed into reduce()
has two required parameters:
accumulator
the running total of the function
currentValue
(shown ascurrentGrade
above)the value of the element in the current iteration
Addition
In addition to the current , the reduce
method also has one optional parameter:
the
initialValue
of the accumulator
We normally start the accumulator with the value of first element in the array. For whatever reason, we can also start the accumulator with any initialValue
:
This allows for any "constant term" (bonusMarks
) added onto the sum of all values;
We do not have to use +=
for the operator; we could use a wide variety of arithmetic operators, but +=
would be the most common use case!
Summary
Remember that reduce()
:
returns a single value
by accumulating the values (most often by addition) of every element in the array
does not modify the original array
in its first parameter, takes in a callback function, which has
an
accumulator
to determine its running totala
currentValue
to determine the value of the current iteration
has an optional parameter that allows for an initial value in the
accumulator
otherwise the
accumulator
takes on the value of the first element in the array
Last updated